gpt4 book ai didi

具有内联模型表单或表单集的基于 Django 类的 View

转载 作者:行者123 更新时间:2023-11-28 19:33:58 25 4
gpt4 key购买 nike

我有以下模型:

class Bill(models.Model):
date = models.DateTimeField(_("Date of bill"),null=True,blank=True)

class Item(models.Model):
name = models.CharField(_("Name"),max_length=100)
price = models.FloatField(_("Price"))
quantity = models.IntegerField(_("Quantity"))
bill = models.ForeignKey("Bill",verbose_name=_("Bill"),
related_name="billitem")

我知道这是可能的:

from django.forms.models import inlineformset_factory
inlineformset_factory(Bill, Item)

然后通过标准 View 处理。

现在我想知道,是否有一种方法可以使用基于类的 View (不适用于管理员-界面)。

最佳答案

重点是:

  1. 使用 inlineformset_factoryforms.py 中生成 FormSet:

    BookImageFormSet = inlineformset_factory(BookForm, BookImage, extra=2)
    BookPageFormSet = inlineformset_factory(BookForm, BookPage, extra=5)
  2. views.pyCreateView 类中返回了 FormSet:

    def get_context_data(self, **kwargs):
    context = super(BookCreateView, self).get_context_data(**kwargs)
    if self.request.POST:
    context['bookimage_form'] = BookImageFormSet(self.request.POST)
    context['bookpage_form'] = BookPageFormSet(self.request.POST)
    else:
    context['bookimage_form'] = BookImageFormSet()
    context['bookpage_form'] = BookPageFormSet()
    return context
  3. 使用 form_valid 保存表单和表单集:

     def form_valid(self, form):
    context = self.get_context_data()
    bookimage_form = context['bookimage_formset']
    bookpage_form = context['bookpage_formset']
    if bookimage_form.is_valid() and bookpage_form.is_valid():
    self.object = form.save()
    bookimage_form.instance = self.object
    bookimage_form.save()
    bookpage_form.instance = self.object
    bookpage_form.save()
    return HttpResponseRedirect('thanks/')
    else:
    return self.render_to_response(self.get_context_data(form=form))

关于具有内联模型表单或表单集的基于 Django 类的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4497684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com