Django:与ModelForm一起使用时,is_valid()方法始终返回false

时间:2020-03-27 10:25:54

标签: python django forms modelform

当我在forms.py中使用forms.ModelForm创建表单时,

is_valid()方法总是返回false,这样我就可以保存从用户输入的表单中获取的所有值。此代码在forms.Form上可以正常工作,但是不适用于forms.ModelForm

forms.py

from django import forms
from .models import student

class student_data(forms.ModelForm):
    name=forms.CharField(widget=forms.TextInput,max_length=20)
    id=forms.IntegerField()
    address=forms.CharField(widget=forms.TextInput,max_length=50)

    class Meta():
        model=student
        fields=['name','stu_id','address']

这是models.py

from django.db import models

# Create your models here.

class student(models.Model):
    name=models.CharField(max_length=20)
    stu_id=models.IntegerField()
    address=models.CharField(max_length=60)

    class Meta:
        db_table='student'

这是views.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import student
from .forms import student_data

def my_data(request):
    stu1_name=''
    stu2_name=''
    stu_name=''
    myform=student_data(request.POST)
    if (request.method=="POST" and myform.is_valid()):
        stu_name=myform.cleaned_data['name']
        stu1_name=myform.cleaned_data['id']
        stu2_name=myform.cleaned_data['address']
        myform.save()
    else:
        myform=student_data
    return render(request,'show.html',{'student':stu_name,'id':stu1_name,'address':stu2_name})

用于表单的html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <form name="form" action="/payment/show/" method="POST">
            {% csrf_token %}
            {{form.as_p}}
            <button type="submit">Add Me</button>
        </form>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

按如下所示更改代码,然后尝试

def my_data(request):
    if request.method == "POST":
        myform = student_data(request.POST)
        if myform.is_valid():
            myform.save()
            return redirect('/')
    else:
        myform = student_data()
    return render(request, '----.html', {'myform': myform})