【发布时间】:2018-01-04 11:32:24
【问题描述】:
我的问题类似于this 问题。唯一的区别是我使用 GCBV 进行分页。我的视图文件如下:
class ChatListView(ListView):
model = Chat
form_class = NewMessageForm
template_name = 'chat.html'
paginate_by = 5
queryset = model.objects.all() ###not needed
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
form.save()
return redirect('chat') <--- here
return render(request, self.template_name, {'form': form})
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = NewMessageForm() # edited: self.form_class
return context
我希望 post 方法重定向到分页的最后一页。在链接中,它是由return HttpResponseRedirect('/forum/topic/%s/?page=%s' % (topic.slug, posts.num_pages))实现的。但是对于我的 GCBV,我不知道如何通过对象获取 .num_pages。请帮忙。
【问题讨论】:
-
queryset = form_class.objects.all()没有意义。它应该类似于queryset = Chat.objects.all()。但是在这种情况下,您根本不必设置queryset,因为您有model = Chat。 -
另外,请注意您在
post中使用self.form_class,但在get中使用NewMessageForm,这是不一致的。 -
是的。编辑查询集。这是一个错字。但是当我不添加查询集时,我的数据库中的对象不会出现。也许它与 post 方法冲突(我不确定)但 queryset 解决了问题。
-
我以为
self.form_class指向NewMessageForm。我应该改成后者吗? -
如果你能删除
queryset = model.objects.all()会更好,因为它不应该是必要的。查看the internals,您可能必须设置self.object_list = self.get_queryset()才能使get_context_data在post请求中工作。
标签: django django-views django-pagination