formset中,有显示信息和填报信息的内容
https://qiita.com/ANKM0/items/8fb032b6af7e64756d69
类似于这个页面
在考核系统中,我是用的 tamplate tag,关联读取显示的信息
{% if field.name == "beikao_user" %}
{{ field }}
{{ userdict|lookup:form.beikao_user.value }}
下面这个例子,是混合了 listview (object_list) 和formset ,通过tag 把2个对象做成tube,挺有趣,使用了第三方lib
pip install Django-Boost
也可以不用 django-boost ,因为这个例子只用了 templatetag zip ,可以学一学这个lib的代码
@register.filter(name="zip") def _zip(arg1, arg2): warn("`zip filter` is deprecated. Use `zip tag` instead.") return zip(arg1, arg2)
class TestData(models.Model): number = models.PositiveIntegerField() name = models.CharField(max_length=200) price = models.PositiveIntegerField() quantity = models.PositiveIntegerField(blank=True, null=True) def __str__(self): return self.name class Meta: verbose_name_plural = "测试数据"
{% extends 'app1/base.html' %} {% load boost %} {% block title %}index{% endblock %} {% block content %} <div class="container"> <h1>index page</h1> <br> <br> {{error_list.0}} <form class="form" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} <div class="bg-light"> <table class="table table-bordered "> <thead> <tr class="table-light"> <th scope="col">商品番号</th> <th scope="col">商品名</th> <th scope="col">価格</th> <th scope="col">数</th> </tr> </thead> <tbody> {% for item, form in object_list|zip:formset %} <tr class="bg-light"> <td> {{ item.number }} </td> <td> {{ item.name }} </td> <td> {{ item.price }} </td> <td> {{ form.non_field_errors }} <div class="form-group"> <label for="{{ form.quantity.id_for_label }}">{{ form.quantity.label_tag }}</label> {{ form.quantity }} {{ form.quantity.errors }} {% for field in form.hidden_fields %} {{ field }} {% endfor %} </div> </td> </tr> {% endfor %} {% for field in form.hidden_fields %} {{ field }} {% endfor %} </tbody> </table> </div> <div class="text-right"> <button type="submit" class="btn btn-primary">送信</button> </div> </form> </div> {% endblock %}
from django.views.generic import TemplateView from django.http import HttpResponse from django import forms from django.shortcuts import render, redirect from .models import TestData class IndexView(TemplateView): template_name: str = "app1/index.html" object_list = TestData.objects.all().order_by("number") max_num = object_list.count() test_data_formset = forms.modelformset_factory( model=TestData, fields=["quantity"], extra=3, max_num=max_num ) def get_context_data(self, **kwargs): # get処理だけ書く ctx = super().get_context_data(**kwargs) # 新規作成formを作る場合は # formset = self.test_data_formset(queryset=TestData.objects.none()) ctx["formset"] = self.test_data_formset() ctx["object_list"] = self.object_list return ctx def post(self, request, *args, **kwargs) -> HttpResponse: formset = self.test_data_formset(request.POST) if formset.is_valid(): formset.save() return redirect("app1:index") context = { "object_list": self.object_list, "formset": formset, } return render(request, self.template_name, context)