[Fixed]-Correct way to add fields to a model on django

1đź‘Ť

âś…

Not sure if I got what you’re looking for but let’s say you want to add a “Status” field to your User model, and then have it in the Admin panel so you can interact with it (update, change, etc…).

in models.py – we are creating a Profile class which will be linked to a User and then a status to be added to a user:

class Profile(models.Model):
    " A profile added User """
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # so to link the profile to a user
    status = models.CharField(max_length=100, blank=True)
    # a field status

    def __str__(self):
        return self.status

in admin.py – we are integrating the newly created Profile to the user

class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    verbose_name_plural = 'Profile'
    fk_name = 'user'

class CustomUserAdmin(UserAdmin):
    inlines = (ProfileInline, )
    def get_inline_instances(self, request, obj=None):
        if not obj:
            return list()
        return super(CustomUserAdmin, self).get_inline_instances(request, obj)

# And then we unregister the User class and register the two updated ones
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

Don’t forget to run /manage.py makemigrations and then /manage.py migrate to update the database.

Let me know if that answer your question.

👤ArokK

Leave a comment