get() keywords must be strings - python-3.x

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.

Related

Getting ProgrammingError at ... using Heroku

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.

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)

How to solve MultipleObjectsReturned with ForeignKeywidget in django-import-export

I have a resource that should help me import data into my model but it doesn't work. I have tried all the options I could but to no success.
This is the resource.
class ImportStudentsResource(resources.ModelResource):
klass = fields.Field(attribute = 'class',column_name='class',widget= ForeignKeyWidget(Klass,'name'))
stream = fields.Field(attribute = 'stream',column_name='stream',widget=ForeignKeyWidget(Stream,'name'))
gender = fields.Field(attribute = 'gender',column_name='gender', widget=ForeignKeyWidget(Gender, 'name'))
school = fields.Field(attribute = 'school',column_name='school', widget=ForeignKeyWidget(School, 'name'))
class Meta:
model = Students
fields = ('school','adm','name','kcpe','klass','stream','gender','notes')
import_id_fields = ('adm',)
import_order = ('school','adm','name','kcpe','klass','stream','gender','notes')
This is the data to import into the model through the resource
This is the Traceback.
Traceback (most recent call last):
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "D:\Python\Django\Links Online Exams\Links_Online_Results\students\views.py", line 52, in post
result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True)
File "D:\Python\Django\Links Online Exams\env\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 "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 788, in import_data_inner
raise row_result.errors[-1].error
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 658, in import_row
self.import_obj(instance, row, dry_run)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 512, in import_obj
self.import_field(field, obj, data)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 495, in import_field
field.save(obj, data, is_m2m)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\fields.py", line 110, in save
cleaned = self.clean(data)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\fields.py", line 66, in clean
value = self.widget.clean(value, row=data)
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\widgets.py", line 396, in clean
return self.get_queryset(value, row, *args, **kwargs).get(**{self.field: val})
File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\query.py", line 433, in get
raise self.model.MultipleObjectsReturned(
students.models.Klass.MultipleObjectsReturned: get() returned more than one Klass -- it returned 2!
Possible cause of the None values
class StudentsForm(forms.ModelForm):
class Meta:
model = Students
fields = ("school","name","adm",'klass',"stream","kcpe","gender","notes")
widgets = {
'school':forms.TextInput(attrs={"class":'form-control','value':'','id':'identifier','type':'hidden'}),
'name':forms.TextInput(attrs={"class":'form-control'}),
}
def __init__(self, school, *args, **kwargs):
super(StudentsForm, self).__init__(*args, **kwargs)
self.fields['klass'] = forms.ModelChoiceField(
queryset=Klass.objects.filter(school=school),label='Class')
self.fields['stream'].queryset = Stream.objects.none()
if 'klass' in self.data:
try:
klass = int(self.data.get('klass'))
self.fields['stream'].queryset = Stream.objects.filter(klass_id=klass).order_by('name')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['stream'].queryset = self.instance.klass.stream_set.order_by('name')
You are violating the ForeignKey constraint with class (klass) (and also stream) row
Jaq / class 2
Lucy / class 2
# only 1 can have 2 as its a ForeignKey
# same error will happen in stream row 4 Eagle 2 Hawk
You should insted of Foreignkey use a ManyToMany field
documentation: https://docs.djangoproject.com/en/3.2/ref/models/fields/#manytomanyfield

Django models: 'ModelFormOptions' object has no attribute 'private_fields'

Even though in the class based view fields = '__all__'. I'm still getting this error
FULL CODE
forms.py
class UploadAlbum(forms.ModelForm):
musicFiles = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
class Meta:
model = Album
exclude = ('music','date',)
views.py
class Rcollection(LoginRequiredMixin,CreateView):
model = UploadAlbum
template_name = 'release/collection.html'
fields = '__all__'
def form_valid(self, form):
# This method is called when valid form data has been POSTed.
# It should return an HttpResponse.
print(form)
return super(Rcollection, self).form_valid(form)
FULL STACKTRACE
kingsley#Number2-Ubuntu:~/Documents/RedRiver$ python3 manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
July 11, 2020 - 15:43:21
Django version 3.0.7, using settings 'RedRiver.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /app/creator/release/rcollection/
Traceback (most recent call last):
File "/home/kingsley/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/kingsley/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/kingsley/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/kingsley/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/home/kingsley/.local/lib/python3.6/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "/home/kingsley/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "/home/kingsley/.local/lib/python3.6/site-packages/django/views/generic/edit.py", line 168, in get
return super().get(request, *args, **kwargs)
File "/home/kingsley/.local/lib/python3.6/site-packages/django/views/generic/edit.py", line 133, in get
return self.render_to_response(self.get_context_data())
File "/home/kingsley/.local/lib/python3.6/site-packages/django/views/generic/edit.py", line 66, in get_context_data
kwargs['form'] = self.get_form()
File "/home/kingsley/.local/lib/python3.6/site-packages/django/views/generic/edit.py", line 32, in get_form
form_class = self.get_form_class()
File "/home/kingsley/.local/lib/python3.6/site-packages/django/views/generic/edit.py", line 101, in get_form_class
return model_forms.modelform_factory(model, fields=self.fields)
File "/home/kingsley/.local/lib/python3.6/site-packages/django/forms/models.py", line 554, in modelform_factory
return type(form)(class_name, (form,), form_class_attrs)
File "/home/kingsley/.local/lib/python3.6/site-packages/django/forms/models.py", line 257, in __new__
apply_limit_choices_to=False,
File "/home/kingsley/.local/lib/python3.6/site-packages/django/forms/models.py", line 144, in fields_for_model
sortable_private_fields = [f for f in opts.private_fields if isinstance(f, ModelField)]
AttributeError: 'ModelFormOptions' object has no attribute 'private_fields'
[11/Jul/2020 15:43:26] "GET /app/creator/release/rcollection/ HTTP/1.1" 500 119649
Maybe you forgot to specify the form attribute in the Rcollection.
form_class = UploadAlbum
And you have to change the model value to Album.
model = Album
form_class= UploadAlbum
remove fields = 'all'

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