我的问题:
MultiValueDictKeyError at /classroom-update/1
"u'student_set-0-id'"
我的观点:
@login_required
def classroom_update(request, pk):
classroom = get_object_or_404(Classroom, pk=pk)
students = classroom.student_set.all()
StudentFormSet = inlineformset_factory(Classroom, Student,form=StudentForm, can_delete=False, extra=0)
if request.method == 'POST':
classroom_form = ClassroomForm(request.POST)
student_formset = StudentFormSet(request.POST)
if classroom_form.is_valid() and student_formset.is_valid():
classroom = classroom_form.save(commit=False)
classroom.user = request.user
classroom.save()
for form in student_formset.forms:
student = form.save(commit=False)
student.classroom = classroom
student.save()
return HttpResponseRedirect('/') # Redirect to a 'success' page
else:
classroom_form = ClassroomForm(instance=classroom)
student_formset = StudentFormSet(instance=classroom)
# For CSRF protection
# See http://docs.djangoproject.com/en/dev/ref/contrib/csrf/
c = {'classroom_form': classroom_form,
'student_formset': student_formset,
}
c.update(csrf(request))
return render_to_response('reports/modify_classroom.html', c)
...和我的模板代码
{% extends 'reports/base.html' %}
{% load crispy_forms_tags %}
{% block head %}
<title>Early Screening Project</title>
{% endblock %}
{% block content %}
<div class="row">
<div class='large-12 columns'>
<form action="" method="POST">{% csrf_token %}
<div class="section">
{% crispy classroom_form %}
</div>
{{ student_formset.management_form|crispy }}
{% for form in student_formset.forms %}
<div class="item">
{% crispy form %}
</div>
{% endfor %}
<input type="submit" value="Submit" class='button' />
</form>
</div>
</div>
{% endblock %}
感谢您的帮助!
答案 0 :(得分:1)
在模板中:
{% for form in student_formset.forms %}
{{ form.id }} #Here , you have to pass form id
<div class="item">
{% crispy form %}
</div>
{% endfor %}
检查:Django docs
干杯
--- Update: You also have to pass the management form {{ formset.management_form }}
- 对评论的回应:
我也有同样的错误,这是修复:
classroom = get_object_or_404(Classroom, pk=pk)
#.....
if request.method == 'POST':
classroom_form = ClassroomForm(request.POST , instance=classroom)
#This is an Update View , missing to add instance , will result a new entry.
student_formset = StudentFormSet(request.POST, instance = classroom)
#passing the instance here would solve the list index out of range
if classroom_form.is_valid() and student_formset.is_valid():
classroom = classroom_form.save(commit=False)
classroom.user = request.user
classroom.save()
for form in student_formset.forms:
student = form.save(commit=False)
student.classroom = classroom
student.save()
return HttpResponseRedirect('/') # Redirect to a 'success' page