如何验证用户

时间:2016-07-05 17:16:58

标签: django django-authentication django-login django-custom-user

我创建了两种不同类型的用户 - truck&公司。这是我的用户enter image description here

的注册页面

注册后,有关用户是卡车还是公司的数据将转到数据库。

在我的登录页面LoginPage

仅输入电子邮件和密码。在我的自定义用户创建表单中,我添加了字段username = email。

当我尝试使用有效凭据登录时,页面不会根据用户类型将我重定向到特定页面。相反,我在login.html中为无效凭据创建的错误正在引发 - “您的电子邮件和密码不匹配。请重试。”

这是我的代码:

views.py:

def login_view(request):
title = "Login"

if request.method == 'POST':

    form = LoginForm(data=request.POST)
    email = request.POST.get('email', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(username=email, password=password)
    if form.is_valid():
        auth.login(request, user)
        user_type = form.cleaned_data['Label']
        if user.is_active & user_type == 'Truck':
            return HttpResponseRedirect('/post_load/')
        elif user_type == 'Company':
            return HttpResponseRedirect('/live_deal/')
else:
    form = LoginForm()

return render(request, 'registration/login.html', {'form' : form, 'title': title})

urls.py:

# url(r'^login/$', views.login_view),
# url(r'^accounts/login/$', views.login_view),
url(r'^login/$', 'django.contrib.auth.views.login', {'authentication_form': LoginForm}),
url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'authentication_form': LoginForm}),

forms.py:

class LoginForm(auth.forms.AuthenticationForm):

email = forms.EmailField(label=_("Email"),widget=forms.EmailInput)
CHOICES= (('Truck', 'Truck'),('Company', 'Company'),)
Label = forms.ChoiceField(choices=CHOICES, label='Label', widget=forms.RadioSelect())

的login.html:

{%extends "registration/header.html"%}
{% block content %}
{% if form.errors %}
<p>Your email and password didn't match. Please try again.</p>
{% endif %}

<form class="form-horizontal" method="post" action = "." >{%csrf_token%}
<div class="panel panel-default login">
        <div class="panel-heading">
            <span class="glyphicon glyphicon-lock"></span> Login</div>
        <div class="panel-body">
            <form class="form-horizontal" role="form">
            <div class="form-group">
                <div class='col-sm-6 col-sm-offset-4'>
                <table border="0">
                <div class="col-sm-4"> 

    <tr><th><label for="id_user" class="col-sm-4 control-label">Email:</label></th><td>{{ form.email }}</td></tr> </div>
    <div class="col-sm-4"> 



    <tr><th><label for="id_password" class="col-sm-4 control-label">Password:</label></th><td>{{ form.password }}</td></tr> </div> 

</table> </div>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-4 col-sm-8">
                    <div class="checkbox">
                        <label>
                            <input type="checkbox"/>
                            Remember me
                        </label>
                    </div>
                </div>
            </div>
            <div class="form-group last">
                <div class="col-sm-offset-4 col-sm-8">
                    <button type="submit" class="btn btn-success btn-sm">
                        Sign in</button>
                    <input type="hidden" name="next" value="/" /> 
                        <label class="col-sm-offset-3">
                 <a href="#">Forget Password? </a>
            </label> 
                </div>
            </div>
            </form>
        </div>
        <div class="panel-footer">
            Not Registered? <a href="/register/">Register</a></div>

</div>
</form>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

{% if form.errors %}
<p>Your email and password didn't match. Please try again.</p>

此错误相当广泛。您可以遍历它以查看实际错误。

更好;不使用您自己的身份验证系统只需使用Django的内置系统,它还允许您向用户模型添加额外的字段。

示例:

from django.contrib.auth import authenticate, login

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            # Redirect to a success page.
        else:
            # Return a 'disabled account' error message
            ...
    else:
        # Return an 'invalid login' error message.
        ...

注意,您不需要编写自己的登录视图,也可以使用Django的登录系统来处理表单,传递重置/更改,网址和模板(您可以使用自己的模板):

网址:

urlpatterns = [
    url('^', include('django.contrib.auth.urls')),
]

然后/login/将成为您的登录页面。

使用Django contrib auth模块后,使用您自己的自定义HTML登录表单进行扩展。

django.contrib.auth.views