嗨,我是Django的新手,需要注册表格和登录信息方面的帮助。我可以注册,并可以查看在管理员注册模型下注册的用户凭证。但是,我试图获取数据库中的用户凭据,然后想要登录,但无法这样做。有人可以帮忙吗。
models.py
class register(models.Model):
name = models.CharField(max_length=250)
username = models.CharField(max_length=20)
password = models.CharField(max_length=20)
occupation = models.CharField(max_length=100)
def __unicode__(self):
return str(self.username)
Views.py
#register
def registerForm(request):
if request.method == 'POST':
if request.POST.get('name') and request.POST.get('username') and request.POST.get('password') and request.POST.get('occupation'):
reg = register()
reg.name = request.POST['name']
reg.username = request.POST['username']
reg.password = request.POST['password']
reg.occupation = request.POST['occupation']
reg.save()
return render(request, 'login.html')
else:
return render(request, 'register.html')
#Login
def Login(request):
if request.method == 'POST':
if request.POST.get('username') and request.POST.get('password'):
usr_login = register()
usr_login.username = request.POST['username']
usr_login.password = request.POST['password']
usr_login.user = authenticate(username=username, password=password)
if usr_login.user:
login(request, usr_login.user)
return HttpResponseRedirect('/forum/')
else:
error = "Username and Password are invalid. Please try again."
return render(request, 'login.html')
else:
return render(request, 'login.html')
login.html
<form method="post" action="/forum/">
{% csrf_token %}
<div class="form-group">
<label for="username">Username:</label>
<input type="username" class="form-control" id="username" placeholder="Enter username" required="required">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" required="required">
</div>
<div class="row">
<div class="col" align="center">
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" type="checkbox"> Remember me
</label>
</div>
<button type="submit" class="btn btn-primary" value="login">Submit</button><br><br>
Not yet registered? <a href="/registeration/">Register Here.</a>
</form>
urls.py
# login
url(r'^login/$', views.Login, name='login'),
# register
url(r'^registeration/$', views.registerForm, name='registeration'),
答案 0 :(得分:1)
您正尝试使用django内置身份验证后端对用户进行身份验证,但未使用django用户模型。在您的情况下,您必须创建自定义身份验证逻辑。我强烈建议您对用户密码进行哈希处理。
如果要使用内置的auth框架,请查看文档以获取更多信息https://docs.djangoproject.com/en/2.1/ref/contrib/auth/