我正在展示两个单独的示例项目。第一个是与联系人相关的,并显示了使用表单向导的原理。第二个是食谱相关项目的成分,它展示了如何在表单中使用内联。我希望内联在我的表单向导中,就像它们以正常形式工作一样。
我有一个表单向导多步表单工作。它基于此处的示例。我已经稍微改变了它以使用模型形式。
模型.py
from django.db import models
# Create your models here.
class Contact(models.Model):
subject = models.CharField(max_length=50)
sender = models.EmailField()
def __unicode__(self):
return self.subject
class Contact2(models.Model):
message = models.TextField(max_length=500)
def __unicode__(self):
return self.message
表格.py
class ContactForm1(forms.ModelForm):
class Meta:
model = Contact
class ContactForm2(forms.ModelForm):
class Meta:
model = Contact2
class ContactWizard(FormWizard):
@property
def __name__(self):
return self.__class__.__name__
def done(self, request, form_list):
# do_something_with_the_form_data(form_list)
return HttpResponseRedirect('/done/')
网址.py
(r'^contact/$', ContactWizard([ContactForm1, ContactForm2])),
另外,我将内联生成为另一种形式。在我看来,我正在通过inlineformset_factory执行此操作。这与上面的表单向导示例无关。这是食谱示例的成分。我这样做是这样的:
视图.py
def add(request):
IngredientFormSet = inlineformset_factory(Recipe, Ingredient,
fk_name="recipe",
formfield_callback=curry(ingredient_form_callback, None))
if request.method == 'POST':
form = RecipeForm(request.POST)
formset = IngredientFormSet(request.POST)
if form.is_valid() and formset.is_valid():
recipe = form.save()
formset = IngredientFormSet(request.POST, instance=recipe)
formset.save()
return redirect("/edit/%s" % recipe.id)
else:
form = RecipeForm()
formset = IngredientFormSet()
return render_to_response("recipes_add.html", {"form":form, "formsets":formset}, context_instance=RequestContext(request))
recipes_add.html
<form method="post">
{% csrf_token %}
<table>
{{ form }}
</table>
<hr>
<h3>Ingredients</h3>
<div class="inline-group">
<div class="tabular inline-related last-related">
{{ formsets.management_form }}
{% for formset in formsets.forms %}
<table>
{{ formset }}
</table>
{% endfor %}
</div>
</div>
<p class="success tools"><a href="#" class="add">Add another row</a></p>
<input type="submit" value="Add">
</form>
如何让内联在我的表单向导多步表单中工作?models.py 现在看起来像这样,因为我希望书籍是内联的。我希望内联出现在我的表单向导的第一步。然后进入第 2 步并完成。
from django.db import models
# Create your models here.
class Contact(models.Model):
subject = models.CharField(max_length=50)
sender = models.EmailField()
def __unicode__(self):
return self.subject
class Contact2(models.Model):
message = models.TextField(max_length=500)
def __unicode__(self):
return self.message
class Book(models.Model):
author = models.ForeignKey(Contact)
title = models.CharField(max_length=100)