简体   繁体   中英

How to authenticate user using custom model in Django?

I am working on a Django project. 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?

models.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

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.

The best way to having a custom user model is that to use AbstractUser. you should do it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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