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?
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.
The __str__ method just tells Django what to print when it needs to print out an instance of the any model.
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With