我通过扩展forms.Form而没有数据库模型来制作Django表单 . 如何在CharField上设置blank = False,以便Django验证将检查字段是否为空?
编辑:在views.py中
def login(request):
if request.method=='POST':
#####
#####
else:
form=LoginForm()
buttontext='Login'
return render(request,'index.html',{'buttontext':buttontext,'form':form})
在forms.py中:
class LoginForm(forms.Form):
username=forms.CharField(label="Username",max_length=30,blank=False)
password=forms.CharField(label="Password",widget=forms.PasswordInput(),blank=False)
class Meta:
help_texts={'username':None,}
def clean(self):
self.cleaned_data=super(LoginForm,self).clean()
u=self.cleaned_data['username']
try:
us=Account.objects.all().get(username=u)
p=self.cleaned_data['password']
print 'original:', us.password
print 'got:', p
if p!=us.password:
add_error('password','Incorrect password')
except Account.DoesNotExist:
self.add_error('username','Username does not exist!')
return self.cleaned_data
2 回答
我上面的评论 - 请勿使用此表单来保存密码,至少not how you're doing it . 但是对于其他形式:你想要
required
,而不是blank
. 空白用于型号,required is for forms .use required = True而不是blank = False
例如:
在Django中,模型中的blank = False与表单中的required = True相关 .