我已经创建了两种不同类型的用户 - 货车和公司。这是我的用户注册页面:
注册后,关于用户是货车还是公司的数据将会存储在数据库中。
在我的登录页面
中,只需要输入电子邮件和密码。在我的自定义用户创建表单中,我添加了字段用户名 = 电子邮件。
当我尝试使用有效凭据登录时,页面没有重定向到特定的用户类型页面。相反,在login.html中,我为无效凭证创建了一个错误提示:“您的电子邮件和密码不匹配,请重试。”
下面是我的代码:
views.py:
![enter image description here](https://istack.dev59.com/8a54o.webp)
在我的登录页面
![LoginPage](https://istack.dev59.com/0xdlP.webp)
当我尝试使用有效凭据登录时,页面没有重定向到特定的用户类型页面。相反,在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 %}