如何在没有Model的Django表单中设置blank = False

时间:2016-10-15 04:23:32

标签: django django-forms

我通过扩展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 个答案:

答案 0 :(得分:1)

use required = True而不是blank = False

e.g:

username=forms.CharField(label="Username",max_length=30,required=True)

在Django中,模型中的blank = False与表格中的required = True相关联。

答案 1 :(得分:1)

我将在上面指出@Daniel Roseman的评论 - 不要使用此表单来保存密码,至少not how you're doing it。但是对于其他表单:您需要required,而不是blank。空白用于模型,required is for forms

class LoginForm(forms.Form):
    username=forms.CharField(label="Username",max_length=30,required=False)
    password=forms.CharField(label="Password",widget=forms.PasswordInput(),required=False)