我按照以下方式设置了我的课程:
class InspectionGroup(models.Model):
group = models.CharField(max_length=50)
class InspectionItem(models.Model):
group = models.ForeignKey(InspectionGroup)
item = models.CharField(max_length=50)
class InspectionQuestion(models.Model):
item = models.ForeignKey(InspectionItem)
question = models.CharField(max_length=200)
question_pass = models.BooleanField()
class InspectionResult(models.Model):
question = models.ForeignKey(InspectionQuestion)
vehicle = models.ForeignKey(Vehicle)
result = models.BooleanField()
submitted_by = models.ForeignKey(User, editable=False)
date_time_submitted = models.DateTimeField(default=datetime.today,
editable=False)
我想要做的是让用户选择一个检查组,然后从该组中向他们呈现该组下的所有问题,其项目标题用于在模板中进行分组。然后他们会回答问题并发布结果。
我的问题是这样做了。我已经开始使用一些代码了,但它似乎不对。
forms.py
QuestionFormSet = inlineformset_factory(InspectionItem, InspectionQuestion,
form=QuestionForm, extra=0, can_delete=False)
class BaseInspectionFormset(BaseInlineFormSet):
def add_fields(self, form, index):
# allow the super class to create the fields as usual
super(BaseInspectionFormset, self).add_fields(form, index)
# created the nested formset
try:
instance = self.get_queryset()[index]
pk_value = instance.pk
except IndexError:
instance=None
pk_value = hash(form.prefix)
# store the formset in the .nested property
form.nested = [QuestionFormSet (instance = instance,
prefix = 'INSPECTIONQUESTIONS_%s' % pk_value)]
InspectionFormset = inlineformset_factory(InspectionGroup, InspectionItem,
formset=BaseInspectionFormset, extra=0, can_delete=False)
view.py
def vehicle_inspection(request, stock_number, id):
vehicle = get_object_or_404(Vehicle, stock_number=stock_number)
group = get_object_or_404(InspectionGroup, pk=id)
if request.method == 'POST':
formset = InspectionFormset(request.POST, instance=group)
if formset.is_valid():
results = formset.save_all()
return HttpResponseRedirect(reverse('inspectionRecord',
kwargs={'stock_number': stock_number}))
else:
formset = InspectionFormset(instance=group)
return render_to_response('vehicles-inspection-form.html', {
'formset': formset})
有人可以确认这个想法是否有用,或者我需要做些什么来获得我想要的功能?目前我收到此错误:
[u'ManagementForm data is missing or has been tampered with']
更新1 我已设法通过此链接from readthedocs
解决上述错误但是,现在,由于模板只显示提交按钮,因此表单似乎是空的。
<form action="." method="POST" id="inspection_form">
{% csrf_token %}
<div id="form">
{{ formset.management_form }}
{% for form in formset.forms %}
{{ form }}
{% if form.nested %}
{% for formset in form.nested %}
{{ formset.as_table }}
{% endfor %}
{% endif %}
{% endfor %}
</div>
<div class="form_buttons">
<button type="submit" name="confirm" id="confirm">
<span>Submit</span>
</button>
</div>
</form>
现在可能出现什么问题?
答案 0 :(得分:1)
文档似乎有答案:https://docs.djangoproject.com/en/dev/topics/forms/formsets/#understanding-the-managementform
编辑:for form in formset
代替formset.forms
?
和{{ form.as_table }}
代替{{ form }}
。