Chubak
Chubak

Reputation: 69

Django form saying "this field is required" (even text fields) although it's been filled

A few other people have had this problem before but they were all file-related. For me, even text fields that I have filled (and must be filled) return "This Field is Required" error whilst I have done everything people suggested. Have a look at my code:

Views

class MainForm(forms.Form):
    name = forms.CharField()
    subject = forms.CharField()
    text = forms.CharField(widget=forms.Textarea)
    file = forms.FileField()
    password = forms.CharField()

def mainpage(request):
    if request.method == 'POST':
        form = MainForm(request.FILES or None, request.POST or None)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponse('Ok')


    else:
        form = MainForm()
    return render(request, "main.html", {'form': form})

def handle_uploaded_file(file):
    name = file.name

    with open(os.path.join("static\img", "{0}".format(name)), 'wb+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)

Template:

{% load staticfiles %}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>{{ siteTitle }}</title>
    <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/main.css">
</head>
<body>
{% include 'header.html' %}

<form enctype="multipart/form-data" method="post">
    {% csrf_token %}
    <table>
    <ul>
        {{ form.as_table }}
    </ul>

    </table>
    <input type="submit" value="Submit" />
</form>


</body>
</html>

It should be noted that when I set everything to non-required, it just returns an empty form.

Thanks for your generous help.

Upvotes: 0

Views: 2331

Answers (1)

solarissmoke
solarissmoke

Reputation: 31404

The order of arguments in your form is wrong - request.POST must come first:

# request.POST must come before request.FILES.
form = MainForm(request.POST, request.FILES)

Also, you don't need the or None. POST and FILES are always present in the request object, even if they are empty.

You probably also don't want those ul tags in the table:

<table>
    {{ form.as_table }}
</table>

Upvotes: 2

Related Questions