Django models: 'ModelFormOptions' object has no attribute 'private_fields' - python-3.x

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'

Related

Using Signals to create data in a Django project once a boolean is changed

I have a question regarding signals. So I have the following model that has a boolean defaulted as False. Once the user clicks on a button to make it true I want to create objects in another model. Here is what I have done but did not create or make any changes:
Here is the Initial Model:
class Initial_Model(models.Model):
active = models.BooleanField(default=False)
Here is the model that I want to create objects once the Initial_Model active boolean becomes True:
class ActiveSession(models.Model):
start_date = models.DateTimeField(auto_now_add=True,blank=True, null=True)
end_date = models.DateTimeField(auto_now_add=True,blank=True, null=True)
#receiver(post_save, sender=Initial_Model)
def create_session(sender, instance, **kwargs):
if Initial_Model.active == True:
ActiveSession.objects.create()
Here is the views.py:
def change_status(request, id):
if request.is_ajax() and request.method == 'POST':
initial_model = Initial_Model.objects.get(id=id)
if request.POST.get('active') == 'true':
initial_model.active = True
initial_model.save()
context = {
'initial_model': initial_model,
'id': initial_model.id,
'status': 'success',
'active': ''
}
html = render_to_string('app/name.html', context,request=request)
start_session= timezone.now()
return JsonResponse({'form': html})
My question is this the correct way of creating the instances in a model. What am I doing wrong and how to fix it.
My required outcome is that when the Initial_Model boolean is switched from False to True a new ActiveSession is added
Using the code below from here is the traceback:
Traceback (most recent call last):
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in in
ner
response = get_response(request)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_r
esponse
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\User\Desktop\Gym_App\my_gym\views.py", line 36, in change_status
initial_model.save()
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\base.py", line 753, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\base.py", line 777, in save_base
pre_save.send(
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\dispatch\dispatcher.py", line 177, in send
return [
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\dispatch\dispatcher.py", line 178, in <list
comp>
(receiver, receiver(signal=self, sender=sender, **named))
File "C:\Users\User\Desktop\Gym_App\my_gym\models.py", line 70, in create_session
obj = sender.objects.get(instance.id)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_
method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\query.py", line 418, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\query.py", line 962, in _filter_o
r_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\query.py", line 969, in _filter_o
r_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\sql\query.py", line 1360, in add_
q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\sql\query.py", line 1379, in _add
_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\sql\query.py", line 1257, in buil
d_filter
arg, value = filter_expr
TypeError: cannot unpack non-iterable int object
you can implement your signal like this:
#receiver(pre_save, sender=Initial_Model)
def create_session(sender, instance, **kwargs):
obj = sender.objects.get(id=instance.id)
if not obj.active and obj.active != instance.active
ActiveSession.objects.create()

'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.

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

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