Anil Beniwal
Anil Beniwal

Reputation: 45

Django ModelForm - Allowing adds for ForeignKey

I'm trying to mimic the functionality from the Django Admin tool where it allows you to add objects for foreign keys (a little plus icon next to a dropdown). For example, let's say I have the following:

class Author(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

class Blog(models.Model):
    name = models.CharField(max_length=50)
    author = models.ForeignKey('Author')

When I go to add my first Blog using a ModelForm for Blog, it shows a dropdown next to Author. However, I have no Authors in the system so that dropdown is empty. In the admin tool, I believe it puts a little "+" icon next to the dropdown so you can quickly and efficiently add a record to the dropdown by opening up a popup.

That is extremely useful, and so I'd like to mimic it in my own app using ModelForms. Is that also built into Django's ModelForms? If so, how do I use it? I can't seem to find anything in the documentation.

Upvotes: 0

Views: 902

Answers (1)

Oswaldo Ferreira
Oswaldo Ferreira

Reputation: 1339

You will need to work with: django.contrib.admin.widgets.RelatedFieldWidgetWrapper

This post certainly will guide you:

Django admin - How can I add the green plus sign for Many-to-many Field in custom admin form

Upvotes: 1

Related Questions