Save multiple models in one form with Django

There is a space in the Advent calendar, so ...

Content of this article

Form-related APIs are relatively generous in Django, but when you try to edit multiple models in one form, it suddenly becomes troublesome.

So, I will be able to do things quickly while using the module.

It's like a continuation of the previous article.

Module to install

django-extra-views

pip install django-extra-views

How to use

That's because django extra views can be done without using a form class.

CreateView

model

models.py


from django.db import models


class Person(models.Model):

    name = models.CharField(max_length=255)
    age = models.IntegerField(default=25) #I want to go back to 25


class Car(models.Model):

    owner = models.ForeignKey(Person)
    color = models.CharField(max_length=10)

views.py

views.py


from extra_views import CreateWithInlinesView, InlineFormSet


class CarInlineFormSet(InlineFormSet):
    model = Car
    fields = ("color", )
    can_delete = False  #No need to delete in create view


class PersonCarCreateFormsetView(CreateWithInlinesView):
    model = Person
    fields = ("name", "age")  # self.model fields
    inlines = [CarInlineFormSet, ]
    template_name = "person_formset.html"
    success_url = "/"

template

person_formset.html


{% extends "base.html" %}

{% block content %}

    <form method="post">
        {% csrf_token %}
        <table>
            {{ form.as_table }}
        </table>

                {#Inline is listed in a variable called inlines#}
        <p>Car Color</p>
        <table>
            {% for form in inlines %}
                {{ form.as_table }}
            {% endfor %}
        </table>
        <button type="submit">save</button>
    </form>

{% endblock %}

UpdateView

model

the same

views.py

views.py


from extra_views import InlineFormSet, UpdateWithInlinesView

class CarInlineFormSetCanDelete(InlineFormSet):
    model = Car
    fields = ("color", )
    can_delete = True

class PersonCarUpdateFormsetView(UpdateWithInlinesView):
    model = Person
    fields = ("name", "age")
    inlines = [CarInlineFormSetCanDelete, ]
    template_name = "person_formset.html"
    success_url = "/"

template

the same

Summary

Very convenient.


Postscript 2017-09-27

How to display other than as_table

If you write it normally, you will want to write the inline one like table.name.

I was a little addicted to it

template.html



{% for inline in inlines %}
  {% for line in inline %}
     {{ line.name }}
  {% endfor %}
{% endfor %}

You can do a double loop like this. This is probably because multiple inline models are set in ʻinlines`.

Postscript up to here


Recommended Posts

Save multiple models in one form with Django
Models in Django
Configure a module with multiple files in Django
Dynamically create tables in schema with Django, dynamically generate models
Save tweet data with Django
How to embed multiple embeds in one message with Discord.py
How to check ORM behavior in one file with django
Django Changed to save lots of data in one go
reload in django shell with ipython
Dynamically add form fields in Django
Switch between multiple models with M5StickV
GraphQL API with graphene_django in Django
Two ways to display multiple graphs in one image with matplotlib
Handle multiple python versions in one jupyter
Handle multiple Django projects with Apache (WSGIDaemonProcess)
Process multiple lists with for in Python
One liner webServer (with CGI) in python
Dynamically add fields to Form objects in Django
Connect multiple videos in one shot using OpenCV!
Start Django in a virtual environment with Pipenv
Build a Django environment with Vagrant in 5 minutes
Easily log in to AWS with multiple accounts
Multiple graphs are displayed in one window (python)
[Python] Dealing with multiple call errors in ray.init
Implementing authentication in Django REST Framework with djoser
Django Contact Form 2
Internationalization with django
CRUD with Django
Django Suggested Form
I want to get an error message in Japanese with django Password Change Form
Django Form Gleaning
Forms in Django
Django contact form
How to get multiple model objects randomly in Django
How to do zero-padding in one line with OpenCV
Set the form DateField to type = date in Django
Implement hierarchical URLs with drf-nested-routers in Django REST framework
How to register the same data multiple times with one input on the Django management screen
[Django] A story about getting stuck in a swamp trying to validate a zip with form [TDD]