简体   繁体   English

如何在 Django 中使用自定义 model 对用户进行身份验证?

[英]How to authenticate user using custom model in Django?

I am working on a Django project.我正在做一个 Django 项目。 The project has three pages Home, login, registration.该项目有首页、登录、注册三个页面。 Home page's nav bar has three buttons Home, login and registration.主页的导航栏有主页、登录和注册三个按钮。 I have created a custom model I don't want to admin model. I already did the login part but now I want is after login the home nav login and register button disappear and a new button/text appear Hello user or whatever the name whoever is logged in. Is there any way to do it I know we can do it with the admin User model but I don't know how to do it with a custom model?我创建了一个自定义 model 我不想管理 model。我已经完成了登录部分,但现在我想要的是登录后主页导航登录和注册按钮消失,新按钮/文本出现你好用户或任何名称已登录。有什么办法吗?我知道我们可以使用管理员用户 model 来完成,但我不知道如何使用自定义用户 model 来完成?

models.py模型.py

class  user_detail(models.Model):
    email = models.EmailField(("email"), max_length=254)
    first_name = models.CharField( ("first name"),max_length=50)
    last_name = models.CharField(("last name"), max_length=50)
    address = models.CharField(("address"), max_length=50)
    phone_number = models.IntegerField(("phone number"))
    password = models.CharField(("password"), max_length=50)

views.py视图.py

from django.shortcuts import render, redirect
from django.views.generic import TemplateView
from .models import user_detail

class loginView(TemplateView):
    template_name = 'accounts/login.html'

    def post(self, request):
        if request.method == 'POST':
            print(request)
            html_email = request.POST['email']
            html_password = request.POST['password']

        user = user_detail.objects.values_list('email',flat = True)
        if html_email in list(user):
            user_password = user_detail.objects.filter(email = html_email).values_list('password',flat = True)[0]
            print(user_password)

            if user_password == html_password :
                return redirect('/home/')
        else:
            print(" incorrect credentials ")

        return render(request, 'accounts/login.html')

Edit: what I need is whenever some is logged in login/register button disappear and welcome,+ first_name.编辑:我需要的是每当有人登录时,登录/注册按钮消失并欢迎,+ first_name。

The best way to having a custom user model is that to use AbstractUser.拥有自定义用户 model 的最佳方法是使用 AbstractUser。 you should do it like this:你应该这样做:

Class User(AbstractUser):
    # add your custom field here
    birth_date=models.IntegerField()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM