我有一種方法將新的Comment
插入到底座中,並且在這樣做之後,它會重定向回到之前的帖子,該帖子可以是任何。因此,要做到這一點,我做了如下規則:傳遞URL參數以呈現
return redirect(reverse('blog:post', args = (post_id,)))
有了它,讀取,通過傳遞到URL中的id
的頁面被重定向回以前Post
。
現在的問題是萬一表格無效。我想顯示錯誤消息,但我認爲現在的方式是重新創建窗體,擦除任何消息。所以,在else
的條件下,我想,而不是重定向,再次呈現並顯示消息。我已經做了這樣的:
return render(request, 'blog/post.html', post_id = post_id)
但後來,我需要找回相同的頁面我,無論id
的參數。我需要像redirect
函數那樣通過post_id
,但我找不到方法。
這是整個方法:用於顯示Post
,這取決於其id
,由URL
def write_comment(request, post_id):
"""
Write a new comment to a post
"""
form = CommentForm(request.POST or None)
if form.is_valid():
post = Post.objects.get(pk = post_id)
post.n_comments += 1
post.save()
comment = Comment()
comment.comment = request.POST['comment']
comment.created_at = timezone.now()
comment.modified_at = timezone.now()
comment.post_id = post_id
comment.user_id = 2
comment.save()
return redirect(reverse('blog:post', args = (post_id,)))
else:
# Need to pass the parameter here, in order to not recreate the form
return render(request, 'blog/post.html')
我的類視圖:
url(r'^post/(?P<id>[0-9]+)/$', views.GetPostView.as_view(), name = 'post'),
而GetPostView
:
class GetPostView(TemplateView):
"""
Render the view for a specific post and lists its comments
"""
template_name = 'blog/post.html'
def get(self, request, id):
return render(request, self.template_name, {
'post': Post.objects.get(pk = id),
'comments': Comment.objects.filter(post = id).order_by('-created_at'),
'form': CommentForm()
})
差不多。該消息最終顯示,但我仍然需要接收'post_id'。該頁面是這個URL'/ post/ /',我需要在同一頁面上呈現頁面。 –
mfgabriel92
所以當你渲染表單驗證錯誤時,你也想要這篇文章?在這個方法中我看不到任何內容(除了重定向)。有沒有另一種方法呢? – bpscott
是的,根據url中的id顯示帖子的類視圖。請看我編輯的問題。 – mfgabriel92