我使用paginator创建一系列满足特定条件的页面
每个页面都包含一个用户可以提交的表单
提交表单后,我希望他们留在/返回他们所在的页面。
我该怎么做?
我到处搜索并阅读文档,但找不到答案
我确定问题出在电脑前,但请帮助:)。
以下是应该执行此操作的视图:
def assignment(request, pk):
"""View for each assignment"""
if request.user.is_authenticated():
#### Get correct articles
assignment = get_object_or_404(Assignment, pk=pk)
country = assignment.country.ccode
start_date = assignment.start_date
end_date = assignment.end_date
articles = Article.objects.filter(country=country).filter(pub_date__range=(start_date,end_date))
paginator = Paginator(articles, 1)
#### Pagination ####
page = request.GET.get('page')
try:
articles = paginator.page(page)
except PageNotAnInteger:
articles = paginator.page(1)
except EmptryPage:
articles = paginator(page(paginator.num_pages))
#### Forms ####
if request.method == 'POST':
if 'event' in request.POST:
event_form = EventRecordForm(request.POST, prefix='event')
if event_form.is_valid():
obj = event_form.save(commit=False)
obj.article = paginator.page(page).object_list[0]
obj.classified = True
obj.coder = request.user.coder
obj.save()
return HttpResponseRedirect(reverse ('coding:assignment', args=(pk,)))
relevance_form = RelevanceCodingRecordForm(prefix='relevance')
elif 'relevance' in request.POST:
relevance_form = RelevanceCodingRecordForm(request.POST, prefix='relevance')
if relevance_form.is_valid():
obj = relevance_form.save(commit=False)
obj.article = paginator.page(page).object_list[0]
obj.screened = True
obj.coder = request.user.coder
obj.save()
return HttpResponseRedirect(reverse ('coding:assignment', args=(pk,)))
event_form = EventRecordForm(prefix='event')
else:
event_form = EventRecordForm(prefix='event')
relevance_form = RelevanceCodingRecordForm(prefix='relevance')
else:
print ERROR
return render(request, 'coding/assignment.html',
{'articles':articles,'assignment':assignment,'event_form':event_form,'relevance_form':relevance_form})
修改
相关建议我将?next={{request.path}}
附加到我的表单操作中
但是,这不起作用,因为分页器页面不包含在路径中。
做他的建议会发生这种情况:
http://127.0.0.1:8000/coding/assignment/1/?next=/coding/assignment/1/
我确实给了paginator第二眼,并认为?page={{ articles.number }}
应该有用,因为在文档的例子中他们做了这样的链接:
<a href="?page={{ articles.next_page_number }}">next</a>
但是,这不起作用
还有其他想法吗?
答案 0 :(得分:0)
我认为页面参数应该在request.path中,因此请尝试将其附加到模板中的提交操作:
?下一= {{Request的}}
并确保您在settings.py文件中将请求作为模板上下文处理器。 (有关详细信息,请参阅https://stackoverflow.com/a/1711592/837845)
答案 1 :(得分:0)
因此,对于每个努力将页面重定向到分页页面的人,我首先要做的是查看主页,因此我将该页面的分页存储在会话中:
request.session['previous_page'] = request.path_info + "?page=" + request.GET.get("page", '1')
现在,在从表单接收POST请求的视图中,返回HttpResponseRedirect:
return HttpResponseRedirect(request.session['previous_page'])