models.py 创建了一个模型 registerForm.my 数据库是mysql。
from django.db import models
class registerForm(models.Model):
name = models.CharField(max_length=50 )
username = models.CharField( max_length=50)
email = models.EmailField(max_length=50)
password = models.CharField(max_length=50)
class Meta:
db_table = 'userForm'
def __str__(self):
return self.name
表格.py
from django import forms
from django.forms import widgets
from login_and_logout.models import registerForm
class regForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
# first call parent's constructor
super(regForm, self).__init__(*args, **kwargs)
# there's a `fields` property now
self.fields['name'].required = False
self.fields['username'].required = False
self.fields['email'].required = False
self.fields['password'].required = False
class Meta:
model = registerForm
fields = "__all__"
视图.py
check form is valid using is_valid() method
def signup(request):
if request.method == 'POST':
form = regForm(request.POST)
print(form.is_valid())
if form.is_valid():
return HttpResponse('success')
else:
return HttpResponse('fail')
form = regForm()
return render(request, 'signup.html', {'form': form})
我试图在客户端使用 javascript 和 dajngo 中的服务器端验证来实现表单验证。为了在没有必需属性的情况下实现表单验证,我在 dajngo forms.py 中给出了必需的 false。但是在 is_valid() 方法之后总是返回 true。但是,如果我删除了用于删除 forms.py 中所需字段的 init 函数,则 is_valid() 有效。我想删除必填字段,并且我想使用 is_valid() 方法。