如何验证用户

How to authenticate a User

我创建了两种不同类型的用户 - 卡车和公司。这是我的用户注册页面

注册后,用户是卡车还是公司的数据会进入数据库。

在我的登录页面,

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

当我尝试使用有效凭据登录时,该页面未根据 user-type 将我重定向到特定页面。相反,我在 login.html 中为无效凭据创建的错误正在引发 - "Your email and password didn't match. Please try again."

这是我的代码:

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 %}
{% 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的登录系统来处理表单,传递reset/change,urls和模板(你可以用自己的模板覆盖):

网址:

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

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

与 Django contrib 身份验证模块一起使用后,使用您自己的自定义 HTML 登录表单对其进行扩展。

django.contrib.auth.views