首页Django正文

loginform.non_field_errors.as_text的用法

提问未结 2 62
lyhabc
lyhabcDjango实战会员2018年9月19日 17:06

登录的视图函数

def user_login(request):
    '''
    用户登录
    :param request:
    :return:
    '''
    if request.method == 'POST':
        loginform = LoginForm(request.POST)
        if loginform.is_valid():
            cleaned_data = loginform.cleaned_data
            user = authenticate(username=cleaned_data['username'], password=cleaned_data['password'])
            if user:
                if user.is_active:
                    login(request,user)
                    print request.session
                    return redirect(reverse('index'))
                else:
                    pass
            else:
                pass

    else:
        loginform = LoginForm()


    context = {
        'loginform': loginform,
    }
    return render(request, 'account/login.html', context=context)

前端模版代码

<form class="login-form" action="{% url 'account:user_login' %}" method="post">
            {%csrf_token%}
            {{ loginform.non_field_errors.as_text }}
            <div class="input-group">
                {{ loginform.username }}
                <label for="id_username" class="input-label">
                    <span class="label-title">用户名</span>
                </label>
            </div>
            <div class="input-group">
                {{ loginform.password }}
                <label for="id_password" class="input-label">
                    <span class="label-title">密码</span>
                </label>
            </div>
            <input id="submit" type="submit"  class="login-button"  value="登录"/>
        </form>

form代码


class LoginForm(forms.Form):
    username = forms.CharField(label='用户名', min_length=2, max_length=20, required=True, widget=forms.widgets.Input(attrs={'class': 'input-field'}))
    password = forms.CharField(label='密码', min_length=5, max_length=20, required=True, widget=forms.widgets.PasswordInput(attrs={'class': 'input-field'}))

    def clean_password(self):
        pwd_len = 10  # 密码不能小于6个字符
        cleaned_data = self.cleaned_data['password']
        if  len(cleaned_data) <= pwd_len:
            raise forms.ValidationError('密码必须大于10个字符!')

        return cleaned_data

问题:输入密码小于10个字符的时候, {{ loginform.non_field_errors.as_text }}没有显示任何报错信息

回帖
  • lyhabc
    lyhabc(楼主)
    2018年9月19日 17:36

    还有一个问题,其他错误,是不是要用变量传递到模版,比如下面代码,用户被禁用这些错误信息是不是要用变量保存错误信息并传递到模版

                if user:
                    if user.is_active:
                        login(request,user)
                        print request.session
                        return redirect(reverse('index'))
                    else:
                        pass
                else:
                    pass
    
  • the5fire
    2018年9月20日 22:42

    其实建议初学者尽量去过一遍文档,不用都记下来,大概知道有哪些内容就行。

    以后根据遇到的问题去看对应文档就好了,比如这个form error的使用:

    https://docs.djangoproject.com/en/2.1/topics/forms/#rendering-fields-manually