user1330734
user1330734

Reputation: 470

Django form FileField error 'This Field is required'

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:

post submission 'This field is required.' error The file has been selected for upload so why would django report field is required?

Upvotes: 5

Views: 4259

Answers (1)

Nazkter
Nazkter

Reputation: 1110

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/

Upvotes: 12

Related Questions