28
votes

In add form for any app in django admin, for foreign key fields of that model.. comes a dropdown list with add button(which opens in a pop-up). Can we have a form where we can add the foreign key model fields in the same form.

For e.g

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    contact = models.ForeignKey(Contact, blank=True, null=True)

For user and contact fields a dropdown with add button is present in admin add form.Can we have all fields of user and contact in same page??

3

3 Answers

20
votes

Yes, you can do that using the inline admin system.

class UserAdmin(admin.StackedInline):
    model = User
class ContactAdmin(admin.StackedInline):
    model = Contact

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

for more details check out https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects .

5
votes

There's a django add-on to get inlines in cases like this where the relationship is the opposite of the usual: django_reverse_admin

You'll need to add django_reverse_admin to your requirements.txt:

-e git+https://github.com/anziem/django_reverse_admin.git#egg=django_reverse_admin

Then import it:

admin.py

from django_reverse_admin import ReverseModelAdmin

class UserProfileAdmin(ReverseModelAdmin):
    inline_reverse = ['user', 'contact']
    inline_type = 'tabular'  # or could be 'stacked'

admin.site.register(UserProfile, UserProfileAdmin)
1
votes

the easiest approach would be something like.

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    contact = models.ForeignKey(Contact, blank=True, null=True)


# Then in the admin create the custom admin view
from .models import Contact

class CustomAdminUserProfile(admin.ModelAdmin):
    list_display = ['contact', 'get_contact_additional_field']

    def get_contact_additional_field(self, obj):
        queryset = Contact.objects.filter(name=obj.name)[0]
        additional_field = queryset.additional_field
        return additional_field

#Then you register
admin.site.register(Contact, CustomAdminUserProfile)