NodeReact020
NodeReact020

Reputation: 506

Django - Form returning invalid due to empty form field

In my project, I have a Django form which consists of an ImageField and a CharField. I pass this form to my template, and display it. On the form, I set the method attribute to POST. In my view I handle this request, and return a redirect in return.

However form.is_valid() is returning False in my view, and I print the forms errors in the console.

Here is the error returned from form.errors:

<ul class="errorlist"><li>image<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

It is saying my ImageField input field is empty, however I definitely select a file for the ImageField in the browser, therefore I don't know the reason why it's saying that the input field is blank. My code is below.

forms.py:

    class CreatePost(forms.Form):
        // The field that is not being assigned a file 
        image = forms.ImageField(allow_empty_file=False, required=True, widget=forms.FileInput(attrs={'id': 'image'}))
        description = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'placeholder': 'Add a caption:', 'id': 'description'}))

views.py:

def create(request):
    context = {}
    if request.method == "POST":
        form = CreatePost(request.POST)
        if form.is_valid():
            print("YES")
            return redirect('home')
        else:
            print(form.errors)
            context['error'] = 'Please enter valid form data'
    else:
        form = CreatePost()

    context['form'] = form
    return render(request, 'create.html', context)

Template:

<form action="{% url 'create' %}" method="POST">
                {% csrf_token %}
                {% for field in form %}
                    {{ field }}
                    <br>
                {% endfor %}
                <button class="createBtn btn btn-primary" type="submit">Post</button>
</form>

Does anybody know the issue here? Thank you.

Upvotes: 1

Views: 649

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

There are two problems here:

  1. you need to pass both request.POST and request.FILES to the form:

    form = CreatePost(request.POST, request.FILES)
  2. in order for a form to submit both files and fields, you need to specify the encoding type to "multipart/form-data":

    <form action="{% url 'create' %}" method="POST" enctype="multipart/form-data">

Upvotes: 1

Related Questions