寫的個人博客中加了一個自己寫的評論框,但是每次提交內容,刷新后,評論框中的文字還存在,而且一旦刷新就會再提交多一次,這個實在令人惱火。
搞了一整天之后,結合網上找的資料,試了一種辦法終於解決了,下面記錄一下:
views.py的函數是這樣的
1 def get_detail(request): 2 try: 3 blogs = Blog.objects.all() 4 comments = Comment.objects.all() 5 except Blog.DoesNotExist: 6 raise Http404 7
9 8 if request.method == 'POST': 11 form = CommentForm(request.POST) 12 print "form:",form 13 if form.is_valid(): 14 print "form.clean():",form.clean() 15 cleaned_data = form.cleaned_data 16 print "type(cleaned_data):",type(cleaned_data) 17 print "cleaned_data['content']:",cleaned_data['content'] 18 19 Comment.objects.create(**cleaned_data) 20 #ctx = { 21 #'blogs':blogs, 22 #'comments':comments, 23 #'form': form 24 #} 25 return HttpResponseRedirect(reverse('blog_get_detail')) #這個函數式關鍵,跳轉回原來的頁面,'blog_get_detail'是urls.py中的一條路由 26 27 28 29 else: 30 form = CommentForm() 31 print "form in the GET:",form 32 33 ctx = { 34 'blogs':blogs, 35 'comments':comments, 36 'form': form 37 } 38 39 return render(request,'blog_detail.html',ctx)
urls.py文件的函數是這樣的
1 urlpatterns = [ 2 url(r'^admin/', admin.site.urls), 3 url(r'^$',blog_views.get_blogs,name="get_blogs"), 4 url(r'^blog/$',blog_views.get_detail,name='blog_get_detail'), #與views.py中提到的HttpResponseRedirect()函數相對應 5 url(r'^photos/$',blog_views.get_photos,name='get_photos'), 6 url(r'^ueditor/', include(DjangoUeditor_urls)), 7 ]
所以,由上面的邏輯關系可以看出
(1)當提交表單內容后,函數會走到return HttpResponseRedirect(reverse('blog_get_detail'))
(2)頁面會刷新一遍,又重新跳轉到def get_detail(request)函數,會走到return render(request,'blog_detail.html',ctx),即原來的頁面,但是評論框的文字已經沒了,這樣就能達到想要的效果