Arjun Kashyap
Arjun Kashyap

Reputation: 663

Why do I get 'this field is required' error in Django models, is there error in my code?

So I am trying to make User form where A user can Upload picture using File-field in models. I am choosing a picture still it says this field is required (after submiting the form) and unloads the pic.

models.py:

# These are our database files for the Incubator Portal
class Incubators(models.Model):
    incubator_name = models.CharField(max_length=30)
    owner = models.CharField(max_length=30)
    city_location = models.CharField(max_length=30)
    description = models.TextField(max_length=100)
    logo = models.FileField()
    verify = models.BooleanField(default = False)

    def get_absolute_url(self):
        return reverse('main:details', kwargs={'pk': self.pk})

incubator-form.html

<form method="post" novalidate>
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Submit</button>
</form>

I have added the following code in site's main urls.py:

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And added the following to settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

I have even created media folder in the project directory. I have another class with same FileField which works fine. The problem is only in this class.

Upvotes: 0

Views: 58

Answers (1)

solarissmoke
solarissmoke

Reputation: 31404

You are missing an enctype attribute on your form tag, which means that the file upload will never reach Django. From the documentation:

Note that request.FILES will only contain data if the request method was POST and the <form> that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty.

You need to update your form tag like so:

<form method="post" novalidate enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>

Upvotes: 1

Related Questions