There is a space in the Advent calendar, so ...
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.
pip install django-extra-views
That's because django extra views can be done without using a form class.
CreateView
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 = "/"
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
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 = "/"
the same
Very convenient.
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