Django表单未经过验证

时间:2016-08-07 00:32:06

标签: python django

我有一个应该从模板验证的表单,两者都如下:

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)

正如我的模板所示:

{% 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>

但每次我通过模板中的表单发送内容时,都没有验证,并且切换到“不正常”。请帮忙。感谢。

修改现在的样子:

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

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

1 个答案:

答案 0 :(得分:2)

一些建议:

  1. including file inputs in the form时,您必须使用正确的<form>代码:

      

    为了上传文件,您需要确保您的元素正确地将enctype定义为“multipart / form-data”:

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

    这可能是验证问题的原因。

  2. Forms API功能强大,可处理rendering forms for you之类的内容。

    你应该使用它,因为默认的渲染器也会显示你当前没有渲染的表单字段错误(所以你无法知道哪些字段无法验证 - 如果你渲染错误,你会知道问题是用文件输入)。

    或者您需要render form errors manually