我正在尝试针对现有数据库对用户进行身份验证。我可以使用他们的电子邮件和密码组合对用户进行身份验证,但我无法保存授权,这意味着用户实际上并未登录。
我知道这是因为在Template.html中,当我致电{% if user and not user.is_anonymous %}
我认为错误来自views.py
auth_login(request, user)
Views.py
from django.contrib.auth import logout as auth_logout
from django.contrib.auth import login as auth_login
from django.contrib.auth import authenticate
...
def login_email(request):
if request.method == 'POST':
email = request.POST.get('email')
password = hashlib.md5(request.POST.get('password')).hexdigest()
#db query to check if email and password combination exist
user = Users.objects.get(email=email,password=password)
if user is not None:
user.backend = 'django.contrib.auth.backends.ModelBackend'
auth_login(request, user)
return redirect('/personalised')
else: #failed to return to login page
return render(request, 'login.html',{})
#invalid POST request recieved
else:
return render(request,"login.html",{})
的login.html
<form action="/login_email/" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="email">Email address</label>
<input type="email" name="email" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="email">Password</label>
<input type="password" name="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-info">Submit</button>
</form>
的 Models.py
class Users(models.Model):
visitorid = models.CharField(db_column='visitorID', max_length=80) # Field name made lowercase.
name = models.CharField(max_length=255)
source = models.CharField(max_length=4)
visits = models.IntegerField()
last_visit = models.CharField(max_length=10)
email = models.CharField(max_length=255)
unsubscribe = models.CharField(max_length=1)
twitter = models.CharField(max_length=100)
password = models.TextField()
.....
template.py
{% if user and not user.is_anonymous %}
<li><a href="/personalised">My Feed </a></li>
<li><a href="/">Trending</a></li>
<li><a href="/recommendations/{{user.username}}">Your Saves</a></li>
<li><a href="/logout">Logout </a></li>
{% else %}
<a href="/login_email?next={{ request.path }}"><button type="button" class="btn btn-success navbar-btn">Sign in with Email</button></a>
{% endif %}
答案 0 :(得分:1)
请勿使用此代码:
email = request.POST.get('email')
password = hashlib.md5(request.POST.get('password')).hexdigest()
#db query to check if email and password combination exist
user = Users.objects.get(email=email,password=password)
而是使用the authenticate
method。它返回User
user = authenticate(email=email, password=password)
这假设您有适当的auth backend设置。