这是我发现问题的解决方案的一般示例:
在
forms.py文件中:
class MyForm(ModelForm): class meta: model = MyModel fields = ('description',)
在
views.py文件中:
from django.core.paginator import Paginator, EmptyPage, PageNotAnIntegerFormSet = modelformset_factory(MyModel, form=MyForm, extra=0)if request.method == 'POST': formset = FormSet(request.POST, request.FILES) # Your validation and rest of the 'POST' preelse: query = MyModel.objects.filter(condition) paginator = Paginator(query, 10) # Show 10 forms per page page = request.GET.get('page') try: objects = paginator.page(page) except PageNotAnInteger: objects = paginator.page(1) except EmptyPage: objects = paginator.page(paginator.num_pages) page_query = query.filter(id__in=[object.id for object in objects]) formset = FormSet(queryset=page_query) context = {'objects': objects, 'formset': formset} return render_to_response('template.html', context, context_instance=RequestContext(request))
您需要使用当前页面中的对象创建表单集,否则,当您尝试
formset = FormSet(request.POST,request.FILES)在POST方法中进行 *** 作时,Django会引发MultiValueDictKeyError错误。
在
template.html文件中:
{% if objects %} <form action="" method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset.forms %} {{ form.id }} <!-- Display each form --> {{ form.as_p }} {% endfor %} <input type="submit" value="Save" /> </form> <div > <span > {% if objects.has_previous %} <a href="?page={{ objects.previous_page_number }}">Previous</a> {% endif %} <span > Page {{ objects.number }} of {{ objects.paginator.num_pages }} </span> {% if objects.has_next %} <a href="?page={{ objects.next_page_number }}">next</a> {% endif %} </span> </div>{% else %} <p>There are no objects.</p>{% endif %}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)