79347767

Date: 2025-01-11 08:55:47
Score: 1.5
Natty:
Report link

I found an easy and perfect sln. Feel free to check, here are my files For reference check on git (https://github.com/bytechtechnologies/Create-CustomUser-in-Django) or YouTube (https://youtu.be/W11uZ8cbWuE)

models.py file

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


class MyUserManager(BaseUserManager):
    def create_user(self, username, phone, password=None):
        user = self.model(
            username=username,
            phone=phone
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, phone, password=None):
        user = self.create_user(
            username=username,
            phone=phone,
            password=password
        )

        user.is_admin = True
        user.save(using=self._db)
        return user


class CustomUser(AbstractBaseUser):
    username = models.CharField(
        max_length=150,
        unique=True
    )
    phone = models.IntegerField()
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = "username"
    REQUIRED_FIELDS = ["phone"]

    def __str__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    @property
    def is_staff(self):
        return self.is_admin

admin.py file

from django import forms
from django.contrib import admin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.contrib.auth.models import Group
from django.core.exceptions import ValidationError
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin

from .models import CustomUser


class UserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label="password", widget=forms.PasswordInput)
    password2 = forms.CharField(label="password confirmation", widget=forms.PasswordInput)

    class Meta:
        model = CustomUser
        fields = ["username", "phone"]

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")

        if password1 and password2 and password1 != password2:
            raise ValidationError("passwords do not match")

        return password2

    def save(self, commit=True):
        user = super().save(
            commit=False
        )

        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()

        return user


class UserChangeForm(forms.ModelForm):
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = CustomUser
        fields = ["username", "phone", "password", "is_active", "is_admin"]


class UserAdmin(BaseUserAdmin):
    form = UserChangeForm
    add_form = UserCreationForm

    list_display = ["username", "phone", "is_admin"]
    list_filter = ["username"]
    fieldsets = [
        (None, {"fields": ["username", "password"]}),
        ("Personal info", {"fields": ["phone"]}),
        ("Permissions", {"fields": ["is_admin"]},
         ),
    ]

    add_fieldsets = [(
        None, {
            "classes": ["wide"],
            "fields": ["username", "phone", "password1", "password2"],
        },
    ),
    ]

    search_fields = ["username"]
    filter_horizontal = []
    ordering = ["username"]


admin.site.register(CustomUser, UserAdmin)

admin.site.unregister(Group)

settings.py file

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'project1app'   # the name of your start app for example I named mine 'project1app'
]

AUTH_USER_MODEL = "project1app.CustomUser"  # name of your start app and name of user class for example my app name is 'project1app' and user class is CustomUser

Reasons:
  • Blacklisted phrase (1): youtu.be
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: user24834406