Getting ProgrammingError at ... using Heroku - python-3.x

I made some changes to my models.py file and now I return this error when I try to access my heroku app's admin page:
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
The above exception (column testingland_mapcafes.cafe_image_url does not exist
LINE 1: ...s"."venue_type", "testingland_mapcafes"."source", "testingla...
^
) was the direct cause of the following exception:
File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 622, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/app/.heroku/python/lib/python3.9/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 236, in inner
return view(request, *args, **kwargs)
File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1828, in changelist_view
'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 262, in __len__
self._fetch_all()
File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 1354, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1202, in execute_sql
cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
Exception Type: ProgrammingError at /admin/testingland/mapcafes/
Exception Value: column testingland_mapcafes.cafe_image_url does not exist
LINE 1: ...s"."venue_type", "testingland_mapcafes"."source", "testingla...
I have tried running heroku run python3 manage.py migrate and get No migrations to apply.
I deleted my migrations cache folder and also manually dropped a column from my Heroku postgres CLI to try and fix things but fear I only made it worse.
Here is the relevant models.py
class mapCafes(models.Model):
id = models.BigAutoField(primary_key=True)
cafe_name = models.CharField(max_length=200)
cafe_address = models.CharField(max_length=200)
cafe_long = models.FloatField()
cafe_lat = models.FloatField()
geolocation = models.PointField(geography=True, blank=True, null=True)
venue_type = models.CharField(max_length=200)
source = models.CharField(max_length=200)
cafe_image_url = models.CharField(max_length=200, null=False)
When I manually check the table through the Heroku DATABASE CLi the cafe_image_url column is not there - suggesting the migration isn't occurring correctly.
FWIW - everything works correctly on my local server.

Related

Django serializers.save() does not use postgres

I have the following function that runs automatically with cronjob, it makes predictions based on an anomaly detection model and it saves the results to a postgres database:
def prediction_job():
"""
This job will run once every batch_minutes minutes to predict if the IPs appear in these batch_minutes minutes are normal or malicious
and save the results to postgres
"""
ip_estimator = IpStatePrediction()
predictions = ip_estimator.predict_ip_state()
predictions_dict_final = convert_dict_for_serializer(predictions)
serializer_result = PredictionsSerializer(data=predictions_dict_final)
if serializer_result.is_valid():
serializer_result.save()
else:
logger.debug("Error with data {}.".format(serializer_result.errors))
When I run it locally after running the commands python3 manage.py runserver and python3 migrate --database postgres, it saves the results to postgres.
However on production I am getting the following error, when the function is executed:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: unrecognized token: ":"
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 108, in debug_sql
yield
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute
return super().execute(sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: unrecognized token: ":"
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler
return func(*args, **kwargs)
File "/anomaly_detection/views.py", line 23, in trigger_prediction_cronjob
prediction_job()
File "/anomaly_detection/access_logs_modeling.py", line 85, in prediction_job
serializer_result.save()
File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 205, in save
self.instance = self.create(validated_data)
File "/usr/local/lib/python3.8/site-packages/rest_framework/serializers.py", line 939, in create
instance = ModelClass._default_manager.create(**validated_data)
File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 447, in create
obj.save(force_insert=True, using=self.db)
File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save
self.save_base(using=using, force_insert=force_insert,
File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 790, in save_base
updated = self._save_table(
File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 933, in _do_insert
return manager._insert(
File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute
return super().execute(sql, params)
File "/usr/local/lib/python3.8/contextlib.py", line 131, in __exit__
self.gen.throw(type, value, traceback)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 113, in debug_sql
sql = self.db.ops.last_executed_query(self.cursor, sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/sqlite3/operations.py", line 155, in last_executed_query
params = self._quote_params_for_last_executed_query(params)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/sqlite3/operations.py", line 144, in _quote_params_for_last_executed_query
return cursor.execute(sql, params).fetchone()
sqlite3.InterfaceError: Error binding parameter 2 - probably unsupported type.

Filtering django admin inline - limit the choices list

Given my inline admin:
class TestInlineAdmin(admin.TabularInline):
model = Test.questions.through
extra = 0
and then
class QuestionAdmin(admin.ModelAdmin):
inlines = [TestInlineAdmin, ]
Test model has question field which is ManyToMany. And i am normally able to edit the question list directly from Test model.
But i want to be able to choose the Tests from inline admin within QuestionAdmin (so, in reverse).
This works. But i need to filter the Test objects in this inline, so the list of choices would show me only Test.objects.filter(applicable=False).
I've tried to use get_queryset, but this seems to have no effect on the choice list, it's only filtering the the actual referenced items in inline, but the list of choices for the new item always shows me the complete unfiltered queryset for Test model.
Overriding formfield_for_manytomany does not work in inline - it's not executed at all.
Would it be possible somehow with formfield_overrides?
Or, as i believe the only way would be to customize the inline form?
-Edit-
My model where the ManyToMany is defined:
class Test(models.Model):
title = models.CharField(max_length=80)
description = models.TextField(null=True)
position = models.ForeignKey('repository.Position', on_delete=models.CASCADE, null=True)
questions = models.ManyToManyField('questions.Question')
applicable = models.BooleanField(default=False)
-- Edited --
traceback after proposal by Willem
2021-09-03 07:50:37 | ERROR | /usr/local/lib64/python3.6/site-packages/django/utils/log.py | log_response | - Internal Server Error: /admin/questions/question/45/change/
Traceback (most recent call last):
File "/usr/local/lib64/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/usr/local/lib64/python3.6/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib64/python3.6/site-packages/django/contrib/admin/options.py", line 614, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib64/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/local/lib64/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/usr/local/lib64/python3.6/site-packages/django/contrib/admin/sites.py", line 233, in inner
return view(request, *args, **kwargs)
File "/usr/local/lib64/python3.6/site-packages/django/contrib/admin/options.py", line 1656, in change_view
return self.changeform_view(request, object_id, form_url, extra_context)
File "/usr/local/lib64/python3.6/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/usr/local/lib64/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/local/lib64/python3.6/site-packages/django/contrib/admin/options.py", line 1534, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "/usr/local/lib64/python3.6/site-packages/django/contrib/admin/options.py", line 1598, in _changeform_view
formsets, inline_instances = self._create_formsets(request, obj, change=True)
File "/usr/local/lib64/python3.6/site-packages/django/contrib/admin/options.py", line 1954, in _create_formsets
for FormSet, inline in self.get_formsets_with_inlines(*get_formsets_args):
File "/usr/local/lib64/python3.6/site-packages/django/contrib/admin/options.py", line 798, in get_formsets_with_inlines
yield inline.get_formset(request, obj), inline
File "/usr/local/lib64/python3.6/site-packages/django/contrib/admin/options.py", line 2053, in get_formset
fields = flatten_fieldsets(self.get_fieldsets(request, obj))
File "/usr/local/lib64/python3.6/site-packages/django/contrib/admin/options.py", line 335, in get_fieldsets
return [(None, {'fields': self.get_fields(request, obj)})]
File "/usr/local/lib64/python3.6/site-packages/django/contrib/admin/options.py", line 326, in get_fields
form = self._get_form_for_get_fields(request, obj)
File "/usr/local/lib64/python3.6/site-packages/django/contrib/admin/options.py", line 2138, in _get_form_for_get_fields
return self.get_formset(request, obj, fields=None).form
File "/usr/local/lib64/python3.6/site-packages/django/contrib/admin/options.py", line 2135, in get_formset
return inlineformset_factory(self.parent_model, self.model, **defaults)
File "/usr/local/lib64/python3.6/site-packages/django/forms/models.py", line 1082, in inlineformset_factory
FormSet = modelformset_factory(model, **kwargs)
File "/usr/local/lib64/python3.6/site-packages/django/forms/models.py", line 879, in modelformset_factory
error_messages=error_messages, field_classes=field_classes)
File "/usr/local/lib64/python3.6/site-packages/django/forms/models.py", line 555, in modelform_factory
return type(form)(class_name, (form,), form_class_attrs)
File "/usr/local/lib64/python3.6/site-packages/django/forms/models.py", line 258, in __new__
apply_limit_choices_to=False,
File "/usr/local/lib64/python3.6/site-packages/django/forms/models.py", line 179, in fields_for_model
formfield = formfield_callback(f, **kwargs)
File "/usr/local/lib64/python3.6/site-packages/django/contrib/admin/options.py", line 172, in formfield_for_dbfield
formfield.widget, db_field.remote_field, self.admin_site, **wrapper_kwargs
AttributeError: 'dict' object has no attribute 'widget'
You can limit the QuerySet of the TestInlineAdmin with:
class TestInlineAdmin(admin.TabularInline):
model = Test.questions.through
extra = 0
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'test':
kwargs['queryset'] = Test.objects.filter(applicable=False)
return super().formfield_for_foreignkey(db_field, request, **kwargs)

'super' object has no attribute 'set_context'

I upgrade Django version from 1.11 to 3.2 and upgrade the installed python.
I am facing an error at this line
super().set_context(serializer_field)
Below is the Full class code.
class UniqueForProjectValidator(UniqueValidator):
def set_context(self, serializer_field):
super().set_context(serializer_field)
self.project = serializer_field.parent.context['project']
def filter_queryset(self, value, queryset):
queryset = queryset.filter(project=self.project)
return super().filter_queryset(value, queryset)
Here is the Error
Traceback (most recent call last):
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\mixins.py", line 82, in partial_update
return self.update(request, *args, **kwargs)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\mixins.py", line 67, in update
serializer.is_valid(raise_exception=True)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\serializers.py", line 220, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\serializers.py", line 419, in run_validation
value = self.to_internal_value(data)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\serializers.py", line 476, in to_internal_value
validated_value = field.run_validation(primitive_value)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\fields.py", line 799, in run_validation
return super().run_validation(data)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\fields.py", line 569, in run_validation
self.run_validators(value)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\fields.py", line 587, in run_validators
validator.set_context(self)
File "C:\Users\arauf\Desktop\innerzone\NewCode\InnerZone-Backend\core\utils.py", line 213, in set_context
super().set_context(serializer_field)
AttributeError: 'super' object has no attribute 'set_context'
It seems you have possibly upgraded Django Rest Framework as well however on Django Rest Frameworks GitHub page, the method set_context does not exist. So your error is telling you, the method set_context on the parent class UniqueValidator does not exist.
See their GitHub page here.

get() keywords must be strings

I can't tell what is the problem, and where the problem is. I was able to upload files through django import export but now I am not able to do so. Here is my Traceback.
Traceback (most recent call last):
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "D:\Python\Django\test projects\library manage\lib_system\Library-System\libman\import_export_views.py", line 227, in post
result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\resources.py", line 741, in import_data
return self.import_data_inner(dataset, dry_run, raise_errors, using_transactions, collect_failed_rows, **kwargs)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\resources.py", line 788, in import_data_inner
raise row_result.errors[-1].error
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\resources.py", line 635, in import_row
instance, new = self.get_or_init_instance(instance_loader, row)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\resources.py", line 330, in get_or_init_instance
instance = self.get_instance(instance_loader, row)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\resources.py", line 323, in get_instance
return instance_loader.get_instance(row)
File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\instance_loaders.py", line 31, in get_instance
return self.get_queryset().get(**params)
TypeError: get() keywords must be strings
This si the resource file
class ImportBooksResource(resources.ModelResource):
def __init__(self, school_id,*args,**kwargs):
super(ImportBooksResource,self).__init__()
self.school_id = school_id
self.fields["id"] = fields.Field(widget=ForeignKeyWidget(Books,'id'))
self.fields['department'] = fields.Field(widget=ForeignKeyWidget(Departments, 'name'))
def before_save_instance(self, instance, using_transactions, dry_run):
instance.school_id = self.school_id
def before_import_row(self, row, **kwargs):
row['department'] = row['department'].lower()
class Meta:
model = Books
fields = ('reg_no','book_name','book_detail','department')
import_id_fields = ('id',)
import_order = ('reg_no','book_name','book_detail','department')
This line looks wrong:
self.fields["id"] = fields.Field(widget=ForeignKeyWidget(Books,'id'))
Remove this line and it should work.
Reason: You are declaring a field on a ModelResource subclass for Books, which points says that there is a FK relation to Books. There shouldn't be an FK relationship to Books from Books. You don't need to declare the id field because you are using ModelResource, hence the field should be available implicitly.

The system cannot find the path specified: error returned when changing field in admin page Django

Hi guys I was just following this tutorial (https://realpython.com/get-started-with-django-1/) to integrate a projects application for my Django portfolio-site project.
Everything was going well with the set up until I tried to log in to admin page of Django to add more objects to my Project model in the database.
After I click add, it return me an error page and it says like this:
Error return page [1]: https://i.stack.imgur.com/co1Cy.png
Traceback
Traceback (most recent call last):
File "C:\Users\username\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\username\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\username\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 607, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\username\anaconda3\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\username\anaconda3\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner
return view(request, *args, **kwargs)
File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 1638, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "C:\Users\username\anaconda3\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\username\anaconda3\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 1522, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 1555, in _changeform_view
ModelForm = self.get_form(request, obj, change=not add)
File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 669, in get_form
fields = flatten_fieldsets(self.get_fieldsets(request, obj))
File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 328, in get_fieldsets
return [(None, {'fields': self.get_fields(request, obj)})]
File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 319, in get_fields
form = self._get_form_for_get_fields(request, obj)
File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 659, in _get_form_for_get_fields
return self.get_form(request, obj, fields=None)
File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 702, in get_form
return modelform_factory(self.model, **defaults)
File "C:\Users\username\anaconda3\lib\site-packages\django\forms\models.py", line 554, in modelform_factory
return type(form)(class_name, (form,), form_class_attrs)
File "C:\Users\username\anaconda3\lib\site-packages\django\forms\models.py", line 257, in __new__
apply_limit_choices_to=False,
File "C:\Users\username\anaconda3\lib\site-packages\django\forms\models.py", line 178, in fields_for_model
formfield = formfield_callback(f, **kwargs)
File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 186, in formfield_for_dbfield
return db_field.formfield(**kwargs)
File "C:\Users\username\anaconda3\lib\site-packages\django\db\models\fields\__init__.py", line 1666, in formfield
**kwargs,
File "C:\Users\username\anaconda3\lib\site-packages\django\db\models\fields\__init__.py", line 927, in formfield
return form_class(**defaults)
File "C:\Users\username\anaconda3\lib\site-packages\django\forms\fields.py", line 1110, in __init__
for f in os.scandir(self.path):
Exception Type: FileNotFoundError at /admin/projects/project/add/
Exception Value: [WinError 3] The system cannot find the path specified: '/projects/img/'
My models.py
from django.db import models
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
image = models.FilePathField(path='/projects/img/')
My file folder look like this
django-project
projects
static
projects
img
-project1.png
-project2.png
-project3.png
...
thanks for the help, I found the bug,
The FilePathField method accepts more explicit path than I thought it needed, so I replaced model with this, It worked like a charm now
from django.db import models
# Create your models here.
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
image = models.FilePathField(path='projects/static/projects/img/')
def __str__(self):
return self.title```
In model Project image field:
Should be project/img not projects/img

Resources