Skip to main content
 首页 » 编程设计

python之django-为什么这个表单总是无效的

2025年05月04日27lyj

我已经创建了一个具有最少字段的表单(用于测试),但它从未进入 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) 

在 forms.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> 

请您参考如下方法:

首先将您的表单传递给 index.html,当请求在 views.py 中不是 POST 时:

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>