具有内联模型形式或表单集的基于django的类的视图

我有以下型号:

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)

然后通过标准视图进行处理。

现在我在想,是否有一种方法可以使用基于类的视图(而不是用于管理界面)来实现相同的目的(意思是:使用内联代码来添加/编辑属于账单的项目)。

回答:

关键点是:

产生FormSet内小号forms.py使用inlineformset_factory

BookImageFormSet = inlineformset_factory(BookForm, BookImage, extra=2)

BookPageFormSet = inlineformset_factory(BookForm, BookPage, extra=5)

FormSet在的CreateView类中返回views.py

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

用于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的类的视图 的全部内容, 来源链接: utcz.com/qa/402563.html

回到顶部