Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 235
A. Sarid Avatar asked Aug 28 '18 21:08

A. Sarid


People also ask

What is ForeignKey Django?

ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases.


1 Answers

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

like image 168
koderstory Avatar answered Oct 09 '22 04:10

koderstory