https://www.pythoneatstail.com/en/overview-all-articles/add-extra-fields-custom-user-model/

 

A custom user model in Django with all common fields - PythonEats

The display name speaks for itself. We have added the possibility of translating the verbose name, by using gettext_lazy. When you are sure you will only use one language, you can of course omit this. In this tutorial we will consistently add the translati

www.pythoneatstail.com

 

1. admin.py

 

 

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser

class CustomUserAdmin(UserAdmin):
    add_form = UserCreationForm
    form = UserChangeForm
    model = CustomUser
    list_display = ['pk', 'email', 'username', 'first_name', 'last_name']
    add_fieldsets = UserAdmin.add_fieldsets + (
        (None, {'fields': ('email', 'first_name', 'last_name', 'display_name', 'date_of_birth', 'address1', 'address2', 'zip_code', 'city', 'country', 'mobile_phone', 'additional_information', 'photo',)}),
    )
    fieldsets = UserAdmin.fieldsets + (
        (None, {'fields': ('display_name', 'date_of_birth', 'address1', 'address2', 'zip_code', 'city', 'country', 'mobile_phone', 'additional_information', 'photo',)}),
    )


admin.site.register(CustomUser, CustomUserAdmin)
  • fieldsets 
    • admin페이지에서 유저 수정할때 나타나는 입력폼 무엇으로 할건지
  • add_fieldsets
    • admin페이지에서 유저 추가할때 나타나는 입력폼 무엇으로 할건지\
  • list_display 
    • admin 리스트에서 보여지는 필드

 

 

2. models.py

 

 

from django.contrib.auth.models import AbstractUser
from django.core.validators import RegexValidator
from django.db import models
from django.utils.translation import gettext_lazy as _
from django_countries.fields import CountryField

class CustomUser(AbstractUser):
    display_name = models.CharField(verbose_name=_("Display name"), max_length=30, help_text=_("Will be shown e.g. when commenting"))
    date_of_birth = models.DateField(verbose_name=_("Date of birth"), blank=True, null=True)
    address1 = models.CharField(verbose_name=_("Address line 1"), max_length=1024, blank=True, null=True)
    address2 = models.CharField(verbose_name=_("Address line 2"), max_length=1024, blank=True, null=True)
    zip_code = models.CharField(verbose_name=_("Postal Code"), max_length=12, blank=True, null=True)
    city = models.CharField(verbose_name=_("City"), max_length=1024, blank=True, null=True)
    country = CountryField(blank=True, null=True)
    phone_regex = RegexValidator(regex=r"^\+(?:[0-9]●?){6,14}[0-9]$", message=_("Enter a valid international mobile phone number starting with +(country code)"))
    mobile_phone = models.CharField(validators=[phone_regex], verbose_name=_("Mobile phone"), max_length=17, blank=True, null=True)
    additional_information = models.CharField(verbose_name=_("Additional information"), max_length=4096, blank=True, null=True)
    photo = models.ImageField(verbose_name=_("Photo"), upload_to='photos/', default='photos/default-user-avatar.png')

    class Meta:
        ordering = ['last_name']

    def __str__(self):
        return f"{self.username}: {self.first_name} {self.last_name}"

 

Django 다국어 지원

from django.utils.translation import gettext_lazy as _
verbose_name=_('안녕하세요.')

 

Django 추가 필드 설치

pip install django-countries

 

 

3. forms.py

 

 

from .models import CustomUser
from wagtail.users.forms import UserCreationForm, UserEditForm


class WagtailUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        widgets = {'date_of_birth': forms.DateInput(attrs={'type':'date'})}


class WagtailUserEditForm(UserEditForm):
    class Meta(UserEditForm.Meta):
        model = CustomUser
        widgets = {'date_of_birth': forms.DateInput(attrs={'type':'date'})}

 

 

4. base.py

 

 

os.path.join(BASE_DIR, 'userauth/templates/userauth/'),
AUTH_USER_MODEL = 'userauth.CustomUser'

WAGTAIL_USER_CREATION_FORM = 'userauth.forms.WagtailUserCreationForm'
WAGTAIL_USER_EDIT_FORM = 'userauth.forms.WagtailUserEditForm'
WAGTAIL_USER_CUSTOM_FIELDS = ['display_name', 'date_of_birth', 'address1', 'address2', 'zip_code', 'city', 'country', 'mobile_phone', 'additional_information', 'photo',]

 

 

5. html

 

 

{% extends "wagtailusers/users/create.html" %}

{% block extra_fields %}
    {% include "wagtailadmin/shared/field_as_li.html" with field=form.display_name %}
    {% include "wagtailadmin/shared/field_as_li.html" with field=form.date_of_birth %}
    {% include "wagtailadmin/shared/field_as_li.html" with field=form.address1 %}
    {% include "wagtailadmin/shared/field_as_li.html" with field=form.address2 %}
    {% include "wagtailadmin/shared/field_as_li.html" with field=form.zip_code %}
    {% include "wagtailadmin/shared/field_as_li.html" with field=form.city %}
    {% include "wagtailadmin/shared/field_as_li.html" with field=form.country %}
    {% include "wagtailadmin/shared/field_as_li.html" with field=form.mobile_phone %}
    {% include "wagtailadmin/shared/field_as_li.html" with field=form.additional_information %}
    {% include "wagtailadmin/shared/field_as_li.html" with field=form.photo %}
{% endblock extra_fields %}

 

1. postgres 설치

pip install psycopg2-binary

 

 

2. 데이터베이스 생성

set PGUSER=postgres
psql
psql -U postgres
CREATE USER usr_pet WITH PASSWORD '123';
CREATE DATABASE db_pet OWNER usr_pet;

 

 

3. base.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'db_pet',
        'USER': 'usr_pet',
        'PASSWORD': '123',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

 

 

4. models.py

 

userauth/models.py

from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    pass

 

 

5. base.py

# custom user model

AUTH_USER_MODEL = 'userauth.CustomUser'

 

+ Recent posts