问题描述
如何从数据库登录?我需要使用来自Bd的表的两个元素(用户和密码)来执行登录。有人知道我需要放入models.py,views.py或更具体的内容的格式,我需要正确登录的内容,谢谢。
解决方法
Django提供了authentication,我建议您检查文档。
在应用程序的models.py部分中,您可以导入内置的User Class以便可以登录。
在模型顶部使用它。py
from django.contrib.auth.models import User
class Post(models.Model):
...
...
author = models.ForeignKey(User)
现在您可以在命令行中创建用户,例如使用:
>>> User.objects.create(username='prozesh',email='prozesh.ir@gmail.com',password='**********')
您还应该在views.py部分中使用身份验证和登录功能来完成工作,但我强烈建议您阅读文档或本article
,尝试使用django的内置身份验证功能对登录进行身份验证。
from django.contrib.auth import authenticate,login
def loginView(request):
if request.method == 'POST':
user = authenticate(username = request.POST['username'],password = request.POST['password'])
if user is not None: # means a user exists in the system
login(request,user) #login function to log user in.
return redirect('/')
if request.user.is_authenticated: # checks if user is already logged in or not
return redirect('/')
如果要使用“ User.objects.create(email,password)”注册新用户
引荐-auth