Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django one-to-many forms

Let's assume I have two models: A and B. A has one-to-many relationship with B i.e. an A can have many B's. If I configure admin properly I can see B's that belong to A and add them dynamically, without refreshing the website. I have an 'Add More' button and I can create many B's within some A. Now I'm looking for example of doing the same thing using standard views and templates. Any suggestions?

like image 482
mnowotka Avatar asked Mar 06 '12 15:03

mnowotka


People also ask

How do you make a one to many relationship in Django?

To define a many-to-one relationship, use ForeignKey . What follows are examples of operations that can be performed using the Python API facilities. Note that you must save an object before it can be assigned to a foreign key relationship.

What is __ str __ In Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is OneToOneField Django?

This field can be useful as a primary key of an object if that object extends another object in some way. For example – a model Car has one-to-one relationship with a model Vehicle, i.e. a car is a vehicle. One-to-one relations are defined using OneToOneField field of django.


2 Answers

As others have pointed out you would need to create an inline formset for your view. The JS used in the admin is based on this project: https://github.com/elo80ka/django-dynamic-formset . It hasn't seen many updates recently but there are examples and some usage docs here: https://github.com/elo80ka/django-dynamic-formset/blob/master/docs/usage.rst

like image 163
Mark Lavin Avatar answered Oct 22 '22 17:10

Mark Lavin


There's nothing really special about what the admin does with inlines (models you edit from change form of another models). It just uses Django's formsets and a bit of javascript to duplicate the actual HTML form. Django's formsets are built to handle an ambiguous amount of forms, so that's really all there is to it.

like image 27
Chris Pratt Avatar answered Oct 22 '22 17:10

Chris Pratt