Show models.ManyToManyField as embedded, with the same form as the models. Foreignkey inline

I have a model similar to the following (simplified):

models.py class Sample(models.Model): name=models.CharField(max_length=200) class Action(models.Model): samples=models.ManyToManyField(Sample) title=models.CharField(max_length=200) description=models.TextField() 

Now, if Action.samples would be ForeignKey instead of ManyToManyField , when I show Action as TabularInline in Sample in Django Admin, I would get several lines, each of which contains a nice form for editing or adding another Action . However; when I post the above as inline using the following:

 class ActionInline(admin.TabularInline): model=Action.samples.through 

I get a selection box that lists all the available actions, and not a great form for creating a new Action .

My question really is: how to display the ManyToMany relation as inline with the form for entering information, as described?

In principle, this should be possible, since from the point of view of Sample situation is the same in both cases; Each Sample has an Action list, regardless of whether the relationship is ForeignKey or ManyToManyRelation . Also; Through the Sample admin page, I never want to select from existing Action s, create only new ones or edit old ones.

+4
source share
1 answer

I see your point of view, but I think about the case when you may need to use a custom model (table). In this case, the built-in admin form will include the fields for this intermediate model, since this is the model that you asked the administrator to create the form for.

eg.

 class Person(models.Model): name = models.CharField(max_length=128) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) 

The administrator must display the form for the Memebership model, which is associated with the model to which the edited instance belongs. In your case, the pass-through model contains only 2 foreign keys (1 for the Action model and 1 for Sample), and therefore only the list of actions appears.

You can do what you ask if django admin supports nested lines ( there is an open ticket about this).

0
source

Source: https://habr.com/ru/post/1304896/


All Articles