我有我想要显示使用Django的分页程序在同一时间10点形成一个模型表单集,但它不能像做paginator = Paginator(formset, 10)
什么是做正确的方式,如果有一种方法?
Answer 1:
这是我发现我的问题的解决方案的一般示例:
在forms.py
文件:
class MyForm(ModelForm):
class Meta:
model = MyModel
fields = ('description',)
在views.py
文件:
FormSet = modelformset_factory(MyModel, form=MyForm, extra=0)
if request.method == 'POST':
formset = FormSet(request.POST, request.FILES)
# Your validation and rest of the 'POST' code
else:
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 class="pagination">
<span class="step-links">
{% if objects.has_previous %}
<a href="?page={{ objects.previous_page_number }}">Previous</a>
{% endif %}
<span class="current">
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 %}
Answer 2:
使用这种比较正确的做法
...
formset = FormSet(queryset=page_query.object_list)
...
Answer 3:
这里的问题是,你正在使用的品牌(一个Page
的情况下),该公司预计,一个QuerySet
。 因此,我们需要那该死的QuerySet
。 你在正确的方式,但大量的代码。
在源代码中,我们有:
class Page(collections.Sequence):
def __init__(self, object_list, number, paginator):
self.object_list = object_list
self.number = number
self.paginator = paginator
...
所以,我们在查询集self.object_list
属性,只是用它!
formset = SomeModelFormSet(queryset=objects.object_list)
文章来源: Paginate Django formset