ankGT
ankGT

Reputation: 123

Django Admin - Prevent Inline Showing When Adding a New Object

I have two one-to-one related models in Django. Simplified version as follows:

class User(models.Model):
    name = models.CharField(max_length=40)

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

I have used signals to automatically create a profile automatically when a new user is created.

I have also created a ProfileInline and included it in my UserAdmin as follows:

class ProfileInline(admin.TabularInline):
    model = Profile
    can_delete = False

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

The problem I am facing is that when a new User is being created in the admin module, and the person creating the new user also populates the field for the inline on the same page, an error is generated while saving because both the signals module and the admin are trying to create a new Profile.

Is there any way to prevent the ProfileInline from showing in the UserAdmin when adding a new User?

Thanks.

Upvotes: 1

Views: 1696

Answers (1)

Pradip Kachhadiya
Pradip Kachhadiya

Reputation: 2235

Add extra=0 in your ProfileInline to prevent create new profile instance when you create new User at admin side...

    class ProfileInline(admin.TabularInline):
        model = Profile
        can_delete = False
        extra = 0
    class UserAdmin(admin.ModelAdmin):
        list_display = ('name',)
        inlines = [ProfileInline,]

OR You can use ModelAdmin get_inline_instances function. Following code removes inlines from add_view:

    class ProfileInline(admin.TabularInline):
        model = Profile
        can_delete = False
    
    class UserAdmin(admin.ModelAdmin):
        list_display = ('name',)
        inlines = [ProfileInline,]
    
        def get_inline_instances(self, request, obj=None):
            return obj and super(UserAdmin, self).get_inline_instances(request, obj) or []

Upvotes: 2

Related Questions