我有两个模型(收据和成分),并希望在创建收据时创建成分。
forms.py
from django import forms
from django.forms import ModelForm
from django.forms.models import inlineformset_factory
from .models import Receipt, Ingredient, CookingStep
class ReceiptForm(forms.ModelForm):
class Meta:
model = Receipt
fields = ('name', 'description', 'hour', 'minute', 'multivarka',)
ReceiptFormSet = inlineformset_factory(Receipt, Ingredient, fields=('name', 'count', 'value'))
models.py
from django.db import models
class Receipt(models.Model):
name = models.CharField(max_length=255)
description = models.TextField(max_length=1024)
hour = models.IntegerField(default=0)
minute = models.IntegerField(default=1)
multivarka = models.BooleanField(default=False)
def __str__(self):
return "%s" % (self.name)
class Ingredient(models.Model):
name = models.CharField(max_length=255)
count = models.IntegerField(default=0) #200gr, 1kg etc
value = models.CharField(max_length=255) #gramm, kg etc
receipts = models.ForeignKey(Receipt)
def __str__(self):
return "%s" % (self.name)
views.py
def receipt_new(request):
if request.method == "POST":
formset = ReceiptForm(request.POST)
if formset.is_valid():
created_receipt = formset.save(commit=False)
new_formset = ReceiptFormSet(request.POST, instance=created_receipt)
if new_formset.is_valid():
created_receipt.save()
new_formset.save()
return redirect('/receipts')
else:
formset = ReceiptForm()
inline_form = ReceiptFormSet()
return render(request, 'admin_site/receipt_edit.html', {'formset': formset})
receipt_edit.html
{% block content %}
<h1>New receipt</h1>
<form method="POST" class="post-form">{% csrf_token %}
{{ formset.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
现在只显示创建收据的表单。我想在编辑页面上有两个表单:首先是收据表单,然后是表单,用于创建此收据的成分(在一页上)。
答案 0 :(得分:0)
首先,为变量使用一些一致的名称。您的ReceiptForm
实例是表单,而不是表单集,因此请将其命名为form
。我们到处拨打您的ReceiptFormSet
实例formset
。
接下来,当您致电render
时,需要在模板上下文中包含表单和formset。
def receipt_new(request):
if request.method == "POST":
form = ReceiptForm(request.POST)
if form.is_valid():
created_receipt = form.save(commit=False)
formset = ReceiptFormSet(request.POST, instance=created_receipt)
if formset.is_valid():
created_receipt.save()
formset.save()
return redirect('/receipts')
else:
form = ReceiptForm()
formset = ReceiptFormSet(instance=Receipt())
return render(request, 'admin_site/receipt_edit.html', {'form': form, 'formset': formset})
最后,您需要在模板中包含表单和formset。
<form method="POST" class="post-form">{% csrf_token %}
{{ form }}
{{ formset }}
<button type="submit" class="save btn btn-default">Save</button>
</form>