A. Sarid
A. Sarid

Reputation: 3996

ForeignKey fields in add/change forms - Django admin

Say I have these models as a simple example:

class Event(models.Model):
    name = models.CharField(max_length=50, default='')
    app = models.ForeignKey(App)

class App(models.Model):
    name = models.CharField(max_length=50, default='')
    app_config = models.ForeignKey(AppConfig)

class AppConfig(models.Model):
    type = models.CharField(max_length=50, default='')
    is_valid = models.BooleanField(default=True)

I want to create an Admin page with add/change forms for Event that will allow me to select an App and create AppConfig with all its fields.

Basically, to have a form with a dropdown to choose an App and below it a form to fill in the AppConfig fields. Or even just a "+" sign or a link that will popup a form to create an AppConfig.

I saw many examples of how to add this to the list_display (such as this) but couldn't manage to do the same with fields or fieldsets in order to have it in the add/change form as well.

Any suggestions will be appreciated. Thanks!

Note: I know that this might be easily solved if I also had AppConfig as a foreign key in Event but this doesn't really make sense.

Edit: My Django and Python versions:
Python: 2.7.x
Django: 1.7.4

Edit2: I have found this nice open-source code django_reverse_admin which might be helpful, but first, this specific package support only Django 2.0+. I tried to use the original code which does seem to support previous Django versions but didn't manage to apply it to my specific case.
If anyone have an idea or can show me how to use this in my specific case it will be great. Thanks!

Upvotes: 9

Views: 2869

Answers (1)

Aldy
Aldy

Reputation: 3102

This package allows you to quickly filter or group "chained" models by adding a custom foreign key or many to many field to your models. This will use an AJAX query to load only the applicable chained objects.

https://github.com/digi604/django-smart-selects

I think, the solution is already talked here How to filter a dropdownlist in Django's admin when a selection is made on another dropdownlist

Upvotes: 3

Related Questions