Skip to content

Latest commit

 

History

History
87 lines (75 loc) · 2 KB

read401-29.md

File metadata and controls

87 lines (75 loc) · 2 KB

Django Custom User

There are two modern ways to create a custom user model in Django: AbstractUser and AbstractBaseUser

Custom User Model:

  1. update config/settings.py *

    INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts', # new
    ]
    ...
    AUTH_USER_MODEL = 'accounts.CustomUser' # new
    
  2. create a new CustomUser model *

    class CustomUser(AbstractUser):
    pass
    # add additional fields in here
    
    def __str__(self):
        return self.username
    
  3. create new UserCreation and UserChangeForm

    class CustomUserCreationForm(UserCreationForm):
    
    class Meta:
        model = CustomUser
        fields = ('username', 'email')
    
    class CustomUserChangeForm(UserChangeForm):
    
    class Meta:
        model = CustomUser
        fields = ('username', 'email')
    
  4. update the admin *

    class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['email', 'username',]
    
    admin.site.register(CustomUser, CustomUserAdmin)
    
  5. Insid app/urls.py add pathes: *

    urlpatterns = [
            path('', TemplateView.as_view(template_name='home.html'), name='home'),
            path('admin/', admin.site.urls),
            path('accounts/', include('accounts.urls')),
            path('accounts/', include('django.contrib.auth.urls')),
    ]
    
  6. Create a urls.py file in the accounts app: *

    urlpatterns = [
    path('signup/', SignUpView.as_view(), name='signup'),
    ]
    
    
  7. in views.py file in the accounts app *

    class SignUpView(CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'
    

Now our registration page created