[英]In my Django portal after login to the portal my request.user is always giving the value AnonymousUser
def login(request):
if request.method == 'POST':
form = AuthForm(request.POST)
if form.is_valid():
userEmail = strip_html(form.cleaned_data['auth_email'])
userPassword = strip_html(form.cleaned_data['auth_password'])
try:
person = Auth.objects.get(auth_email=userEmail, auth_password=userPassword)
request.session['username'] = person.auth_name
return redirect("/crudapplication/show")
except:
page = 'login.html'
message = 'Username doesn\'t exist'
Above is a small code snipet.上面是一个小代码片段。 This is my login functionality.So the value of the user email and password I'm providing is present in my database.
这是我的登录功能。所以我提供的用户电子邮件和密码的值存在于我的数据库中。
So when I'm printing the line on console by print(request.user) it always gives the value Anonymoususer.因此,当我通过 print(request.user) 在控制台上打印该行时,它总是给出值 Anonymoususer。 The login function is the part of views.py of my login module
登录功能是我的登录模块的views.py的一部分
You're doing authentication in a very manual way.您正在以非常手动的方式进行身份验证。 The problems this can cause are 2:
这可能导致的问题是 2:
The objective of using django that is a framework is not to have to do the work from 0, therefore it uses the tools that django has.使用框架 django 的目的不是必须从 0 开始工作,因此它使用了 django 拥有的工具。
For this case use the django authentication system:对于这种情况,请使用 django 身份验证系统:
https://docs.djangoproject.com/en/3.0/topics/auth/default/ https://docs.djangoproject.com/en/3.0/topics/auth/default/
The above is the official documentation, however to understand how authentication works on a personal level I was more helped by the following tutorial:以上是官方文档,但是为了了解身份验证如何在个人层面上工作,我从以下教程中得到了更多帮助:
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication
def login_user(request):
print(request.POST)
username = request.POST['username']
password = request.POST['password']
print(username)
print(password)
user = authenticate(request, username=username, password=password)
print(user)
if user is not None:
login(request, user)
return redirect("/crudapplication/show")
...
else:
# Return an 'invalid login' error message.
return render(request, 'login.html')
Above is my views.py file and below I'm mentioning my template file.上面是我的 views.py 文件,下面是我的模板文件。
<form method="post" action="/authLogin/login/">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
Everything works fine now..but i just wanted to know the form object that I'm using in my template file how will I pass this objevt from my views.py file?现在一切正常..但我只想知道我在模板文件中使用的表单对象我将如何从我的 views.py 文件中传递这个对象?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.