django - 为什么这个表格总是无效的

时间:2013-08-01 12:12:04

标签: python django django-forms

我创建了一个包含最少字段的表单(用于测试),但它从不输入 form.is_valid()

这是最小代码

models.py

中的

 from django.db import models

 class sample(models.Model):
      field1=models.CharField(max_length=100)
      field2=models.CharField(max_length=100)
form.py

中的

from django.forms import ModelForm
from app.models import sample

class someform(ModelForm):
      class Meta:
        model=sample
在views.py中

some imports

def index(request):
    return render(request, 'app/index.html')

def contact(request):
    if request.method=='POST':
         form=someform(request.POST)
         if form.is_valid():
            field1=form.cleaned_data['field1']
            field2=form.cleaned_data['field2']
            return HttpResponse("valid")
         else:
            return HttpResponse("invalid")
    else:
            form=someform()
            return HttpResponse("error")

问题是,它永远不会进入(如果是form.is_valid())。我错过了什么吗?请帮忙

index.html中的

<html>
      <body bgcolor="#2E9AFE">
      <form action="contact" method="post" enctype="multipart/form-data">
      {% csrf_token %}
      <input type="text" id="field1" name="field1">
      <input type="text" id="field2" name="field2">
      <input type="submit" id="submit" name="submit">
      </form></body></html>

2 个答案:

答案 0 :(得分:4)

如果请求不是在views.py中的POST:

,首先将表单传递给index.html
else:
            form=someform()
            return render(request, 'index.html', locals())

在模板中你应该这样:

<form action="contact" method="POST" xmlns="http://www.w3.org/1999/html">
    {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn">Submit</button>
</form>

答案 1 :(得分:3)

当收到POST查询时,Django正在寻找ID id_field1id_field2的2个字段,因此您的HTML将如下:

<html>
   <body bgcolor="#2E9AFE">
      <form action="contact" method="post" enctype="multipart/form-data">
        {% csrf_token %}
         <input type="text" id="id_field1" name="field1">
         <input type="text" id="id_field2" name="field2">
         <input type="submit" id="submit" name="submit">
         </form>
   </body>
</html>

另一种解决方案是使用{{ form.as_p }}{{ form.as_table }}自动在

或标签内呈现输入。

您还可以在当前HTML中添加{{ form.non_field_errors }}{{ form.field1.errors }}{{ form.field2.errors }},以便在验证失败时显示表单错误。

相关问题