Reputation: 69
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():
handle_uploaded_file(request.FILES['file'])
return HttpResponse('Ok')
else:
return HttpResponse('not ok')
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)
And as my template goes:
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en" 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 method="post">
{% csrf_token %}
<label class="label" for="name">Name</label>
<input id="namebox" type="text" name="name" />
</br>
<label class="label" for="subject">Subject</label>
<input id="subjectbox" type="text" name="subject" />
</br>
<label class="label" for="text">Text</label>
<textarea id="textedit" name="text"></textarea>
</br>
<label class="label" for="file">File</label>
<input type="file" name="file" />
</br>
<label class="label" for="password">Password</label>
<input type="password" id="passwordbox" name="password" />
</br>
<input type="submit" />
</form>
</body>
</html>
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 %}
<table>
<ul>
{{ form.as_table }}
</ul>
</table>
<input type="submit" value="Submit" />
</form>
Upvotes: 0
Views: 69
Reputation: 31404
A couple of suggestions:
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.
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.
Upvotes: 2