Gorgonzola
Gorgonzola

Reputation: 401

Django: Reference user's first_name using AbstractUser?

My goal is to add non-authentication values to a user. Like, bio, nationality, etc. I am trying to use a custom user model. I am having trouble accessing the values. I can use the new ones I created, but not the original ones like first_name, last_name, email.

my model.py looks like

from django.db import models

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    bio = models.CharField(max_length=500, blank=True)    
    phone = models.CharField(max_length=20, blank=True)

Settings.py I added:

AUTH_USER_MODEL = 'publication.User'

INSTALLED_APPS = [
    'publication.apps.PublicationConfig,
    ...

My admin.py:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User

admin.site.register(User, UserAdmin)

How to I add bio and nickname to the admin page?

And how do I access first name, email, bio, phone outside in forms and such?

Many thanks.

Upvotes: 0

Views: 655

Answers (2)

Gorgonzola
Gorgonzola

Reputation: 401

Adding to @gdef_'s answer,

The best way to add information to a user I found was to do a custom user model using Abstractuser. This simplified things a lot. This has to be done early in the project before the first migration, actually, I would recommend this to be done every time. I will use this from now on.

Things worth noting, when registering models in admin.py. The abstract models should be registered this way:

admin.site.register(CustomUser,CustomUserAdmin)

but for other models use a decorator:

@admin.register(Story)
class StoryAdmin(admin.ModelAdmin):
    list_display = ('id','title','get_date_formatted', 'author')
    ... 
    more stuff

Upvotes: 0

gdef_
gdef_

Reputation: 1936

You are using Django's UserAdmin, that is adding all the things you see in the admin forms for your user. You can see the code here.

If you want to add your fields you need to create a custom model admin class from scratch or extend the one you want. You can extend and override things in the UserAdmin that you are using. Check the structure of add_fieldsets and fieldsets, adding fields to those tuples will add them to the admin.

For example to add bio and phone to the form:

@admin.register(models.User)
class CustomUserAdmin(UserAdmin):
    fieldsets = (
        (None, {'fields': ('bio', 'phone')}),
    ) + UserAdmin.fieldsets
    add_fieldsets = (
        (None, {'fields': ('bio', 'phone')}),
    ) + UserAdmin.fieldsets

Read more about how to customize the admin here.

Upvotes: 1

Related Questions