Issue
I am receiving a This field is required error using a form view that django is generating.
I have a Scan model that looks like:
class Scan(models.Model):
device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL)
created_at = models.DateTimeField('Created', auto_now=True)
data = models.FileField(upload_to='uploads/')
def __str__(self):
return str("{}-{}".format(self.device, self.created_at))
I have a CreateView defined:
class ScanCreate(LoginRequiredMixin, CreateView):
model = Scan
fields = '__all__'
My url route is
urlpatterns = [
...
path('scan/create/', views.ScanCreate.as_view(), name='scan-create'),
...
]
and finally a scan_form.html template
{% block content %}
<form action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
{% endblock %}
On picking a file to upload and submitting the form, I get the 'This field is required.' error and the request fails:
The file has been selected for upload so why would django report field is required?
Solution
The main problem in you code is that you are not using enctype="multipart/form-data"
in your form, so when the request is sent to the server, it does not have the file in the request.FILES
collection.
you have to write the html code for your form like this:
{% block content %}
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
{% endblock %}
and ensure that the action is pointing to the correct URL.
finally, this is the documentation for file uploads: https://docs.djangoproject.com/en/stable/topics/http/file-uploads/
Answered By - Nazkter
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.