分页Django表单集

分页Django表单集,第1张

分页Django表单

这是我发现问题的解决方案的一般示例

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 %}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5427364.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存