Home > database >  Django - Custom model cannot appear on User model
Django - Custom model cannot appear on User model

Time:06-12

I have created a model in Django v4, and I want to show the information inside the User admin view. After migrating, a new table was created successfully and data is being stored. Here is the code:

models.py

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE
    )

    address = models.CharField(
        max_length=20,
        blank=True,
        null=True
    )

    def __str__(self):
        return self.user.username

admin.py

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

class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    verbose_name_plural = 'Extra Information'

@admin.register(ProfileInline)
class UserAdmin(admin.ModelAdmin):
    inlines = [
        ProfileInline,
    ]

The table that has been created has the following stored:

id address user_id
3 Test 2

Where the user_id column, is a foreign key from the auth_user table, which is created automatically (I guess?).

Now, when I try to run, makemigrations, etc, it shows me the following:

AttributeError: type object 'ProfileInline' has no attribute '_meta'

What is the proper way to have the information appended to the User, as the default sections do?

CodePudding user response:

I figured out the solution. The admin.py should look like this:

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

class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    verbose_name_plural = 'Extra Information'

class UserAdmin(admin.ModelAdmin):
    inlines = [
        ProfileInline,
    ]

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

CodePudding user response:

A better approach in this case would be to inherit Django's AbstractUser class, add your additional fields then set Django's AUTH_USER_MODEL in settings so that django uses your model for authentication. https://docs.djangoproject.com/en/4.0/ref/settings/#std-setting-AUTH_USER_MODEL

models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class Profile(AbstractUser):
    address = models.CharField(
        max_length=20,
        blank=True,
        null=True
    )

    def __str__(self):
        return self.username

settings.py

AUTH_USER_MODEL = "<your_app_name>.Profile"
  • Related