0

无论我的输入是什么以及不管显示错误的方法如何,我都会在我的登录表单上显示错误。Django:在提交表单时未显示错误

在我的CustomUserCreationForm错误显示完美的作品。两者之间的唯一区别是登录扩展forms.Form而自定义扩展UserCreationForm

而且我使用Django的脆皮形式来呈现我的形式

class LoginForm(forms.Form): 
    username = forms.CharField(label=('UserName'), 
      widget = forms.TextInput(attrs={'placeholder': _('Username')}) 
    ) 
    password = forms.CharField(label=('Password'), 
      widget=forms.PasswordInput(attrs={'placeholder' : _('Password') }), 
    ) 

    def helper(self): 
      helper = FormHelper() 

      helper.form_id = "Login" 
      helper.form_method = "POST" 
      helper.layout = Layout(Div(
        Field('username', css_class='input-box-rounded'), 
        Field('password', css_class='input-box-rounded'), 
        Submit('Login', 'Login', css_class='col-md-6 col-md-offset-3 rounded'), 
        css_class='col-md-4 col-md-offset-4 centered-div')) 
      return helper 

    def clean(self): 

      cleaned_data = super(LoginForm, self).clean() 

      if 'username' not in cleaned_data: 
        msg = _("Please enter a username") 
        self._errors['username'] = self.error_class([msg]) 
      if 'password' not in cleaned_data: 
        msg = _("Please enter a password") 
        raise forms.ValidationError(msg) 
      u =authenticate(username = cleaned_data['username'], password = cleaned_data['password']) 
      if u == None: 
        msg = _("Username or Password is incorrect") 
        self.add_error('username', msg) 

      return cleaned_data 

回答

1

你可以发布你的观点和模板代码?没有看到其中任何一个,我假设你的模板需要显示错误,或者你的视图没有处理表单,尽管我没有使用过Django Crispy Forms。

{{ form.non_field_errors }} 
{{ form.username.errors }} 

仅供参考,以处理错误检查的首选方法是创建的每个字段清洁功能,并将它提升一个ValidationError时,有一个问题。这将是一个现场错误(上面的第二行)。

def clean_password(self): 
    data = self.cleaned_data.get('password') 
    if not data: 
     raise ValidationError(_("Please enter a password")) 

而且,因为你只检查一个字段是存在的,所以你可以设置required=True每个必填字段,并跳过手动验证。

class LoginForm(forms.Form): 
    username = forms.CharField(label=('UserName'), required=True, 
     widget = forms.TextInput(attrs={'placeholder': _('Username')}) 
    ) 
    password = forms.CharField(label=('Password'), required=True, 
     widget=forms.PasswordInput(attrs={'placeholder' : _('Password') }), 
    ) 

见文档的详细信息:https://docs.djangoproject.com/en/dev/topics/forms/#customizing-the-form-template