我创建了两种不同类型的用户 - truck&公司使用Django。这是我的用户Registration Page
的注册页面注册后,有关用户是卡车还是公司的数据将转到数据库。
我想知道具有唯一EmailID的用户如何根据用户类型重定向到有效页面。
我认为,身份验证和从POST请求(在views.py中)获取数据到我的登录页面是不能正常工作的。请有人帮我解决这个问题。
这是我的代码:
views.py:
@csrf_protect
def login_view(request):
title = "Login"
if request.method == 'POST':
email = request.POST.get('email', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=email, password=password)
form = LoginForm(data=request.POST)
if form.is_valid():
user_type = form.cleaned_data['Label']
if 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/$', '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 %}
答案 0 :(得分:0)
以下是查看视图中无线电字段的更好方法: -
user_type = form.cleaned_data['Label']
if user_type == 'truck':
# send the user to truck page
else:
# send the user to company page
还有一些事情 - 一旦你使用is_valid()进行验证,你真的不需要调用那个clean()方法,你应该在那个POST部分中移动那个authenticate()的东西。