【问题标题】:Check email and password from custom database tables in django从 django 中的自定义数据库表中检查电子邮件和密码
【发布时间】:2021-12-05 14:57:34
【问题描述】:

我正在为我的大学创建一个网站,学生可以在其中注册和登录,数据将存储在我的自定义表“studentlogin”中。

我已经在我的数据库表中收集和存储用户数据,但现在我被困在如何比较这些数据以检查电子邮件和密码是否正确

我从某个地方找到了这个解决方案

add "django.core.context_processors.request" in your context processors in settings.py

def loginView(request):
# after checking if the user is active, exists and passwword matches
  request.session["isLoggedIn"] = True
  request.session["username"] = request.POST.get("username")

{% if request.session.isLoggedIn %}
{{request.session.username}}

{% else if not request.session.isLoggedIn %}
<p>User not in session or logged off</p>
{% endif %}

但我很困惑将这段代码放在哪里!?

我想第一个代码块要添加到views.py 中的studentlogin 视图中?

【问题讨论】:

  • 您要对用户进行身份验证吗?
  • 你为什么不使用 Django 的身份验证后端?您甚至可以使用自定义用户模型。另外,请不要在您的数据库中存储纯文本密码:)
  • @bichanna 是的,但我将用户数据存储在自定义数据库表中
  • @GregKaleka 真的,我怎样才能将 django 的身份验证后端与自定义用户模型一起使用??
  • 有几种方法。这是一篇关于一些选项的好博文:simpleisbetterthancomplex.com/tutorial/2016/07/22/…

标签: python django django-users django-login


【解决方案1】:

这是你想要的吗?:

from django.contrib import auth

user = auth.authenticate(email=email, password=password)
if user is not None:
    auth.login(request, user)
    # do whatever you want here
else:
    # when credentials are not right...

【讨论】:

  • 这会放在 models.py 中,对吧?
  • 没有。你把它写在views.py中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
  • 2018-07-06
  • 1970-01-01
  • 2020-06-17
  • 2023-02-03
相关资源
最近更新 更多