Yes, to create a user model in Django, you can use the built-in User model provided by Django's authentication system or create your own custom user model. Here is an example of how to create a custom user model:

from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models

class CustomUserManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError('The Email field must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        return self.create_user(email, password, **extra_fields)

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name']

    objects = CustomUserManager()

    def __str__(self):
        return self.email

This custom user model includes the email, first name, last name, and password fields. It also includes the is_active and is_staff fields, which are used for authentication and authorization purposes. The CustomUserManager class provides methods for creating regular and superusers. Finally, the CustomUser class inherits from Django's AbstractBaseUser and PermissionsMixin classes and defines the required fields and methods for a custom user model.

can u create a user model django

原文地址: https://www.cveoy.top/t/topic/btNJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录