Chubak Chubak - 1 year ago 45
Python Question

Django form is not validated

I have a form that should be validated from the template, which both are as follows:

from django.shortcuts import render
from django.forms import Form
from django import forms
from django.http import HttpResponse
import MyIB.settings
import os

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

def mainpage(request):
if request.method == 'POST':
form = MainForm(request.POST, request.FILES)

if form.is_valid():
return HttpResponse('Ok')
return HttpResponse('not ok')

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

def handle_uploaded_file(file):
name =

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

And as my template goes:

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

<form method="post">
{% csrf_token %}
<label class="label" for="name">Name</label>
<input id="namebox" type="text" name="name" />
<label class="label" for="subject">Subject</label>
<input id="subjectbox" type="text" name="subject" />
<label class="label" for="text">Text</label>
<textarea id="textedit" name="text"></textarea>
<label class="label" for="file">File</label>
<input type="file" name="file" />
<label class="label" for="password">Password</label>
<input type="password" id="passwordbox" name="password" />
<input type="submit" />


But every time I send something via the form in my template, it's not validated and it switches to "not ok". Please help. Thanks.

Edit How it is now:

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

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

Answer Source

A couple of suggestions:

  1. When including file inputs in the form, you have to use the right <form> tag:

    In order to upload files, you’ll need to make sure that your element correctly defines the enctype as "multipart/form-data":

    <form enctype="multipart/form-data" method="post" action="/foo/">

    This is probably the cause of your validation issue.

  2. The Forms API is powerful and handles things like rendering forms for you.

    You should use this because the default renderer will also display form field errors which you currently aren't rendering (so you have no way of knowing what field failed to validate - if you were rendering errors you would know that the issue was with the file input).

    Alternatively you need to render form errors manually.