【问题标题】:How to authenticate user by custom model in Django如何在 Django 中通过自定义模型对用户进行身份验证
【发布时间】:2020-09-26 07:50:45
【问题描述】:

我想使用我的自定义模型对用户进行身份验证,但在登录页面上,用户仅通过 Django 管理员凭据登录。我想做的就是通过我的自定义模型对用户进行身份验证

请帮助处理此代码我无法使用自定义模型创建用户身份验证。

这是models.py文件

from django.db import models
from phonenumber_field.modelfields import PhoneNumberField`

#Create your models here.

    class registerdata(models.Model):
        name = models.CharField(max_length=50)
        email = models.CharField(max_length=70, default="")
        phone = PhoneNumberField(null=False, blank=False, unique=True)
        password = models.CharField(max_length=500, default="")
        def __str__(self):
            return self.name
    #here is views.py of app
    from django.shortcuts import render,redirect
    from django.http import HttpResponse 
    from django.contrib import messages`
    from .models import registerdata
    from django.contrib.auth.models import User,auth
    from django.contrib.auth import logout`
    # Create your views here.
    def login(request):
        #code for checking authentication 
        if request.method == "POST":
            print(request.POST)
            username=request.POST.get("username")
            password=request.POST.get("password")
            user = auth.authenticate(username=username,password=password)
            if user is not None:
                print('auth pass')
                auth.login(request, user)
                return redirect('chats')
            else:
                print('auth fail')
                messages.info(request,"invalid credentials")
                return redirect('loginpage')
        return render(request,'login.html')
    def Register(request):
        if request.method=="POST":
            name = request.POST.get('name', '')
            email = request.POST.get('email', '')
            phone = request.POST.get('phone', '')
            password= request.POST.get('password','')
            Register = registerdata(name=name, email=email, phone=phone, password=password)
            Register.save()
            return redirect('loginpage')  
        return render(request, 'register.html')
    def chats(request):
        if request.user.is_authenticated:
            logout(request)
            return render(request,'chats.html')
        else :
            return redirect('loginpage')

urls.py

from django.urls import path
from .import views

    urlpatterns = [
        path('', views.chats, name='chats'),
        path('login/', views.login, name='loginpage'),
        path('Register/', views.Register, name='Register'),
    ]

【问题讨论】:

标签: django django-models django-authentication


【解决方案1】:

问题是您的自定义用户模型不完全是 django 自定义用户,而只是在数据库中有表的普通模型,并且您不能在模型上使用任何 django auth 相关功能。看看这个article,了解你应该如何实现自定义用户模型

【讨论】:

    猜你喜欢
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    相关资源
    最近更新 更多