its-django / mysite

<<It's Django - 用Python迅速打造Web應用>> 書中程式碼
Apache License 2.0
48 stars 25 forks source link

Module10 comment csrf 驗證失敗 #12

Open rhybs opened 8 years ago

rhybs commented 8 years ago

樓下也有人類似的問題 最後他的code順利執行 於是我使用了樓下的comments.html(已刪除空白) 卻也是有一樣的狀況 因此先排除comments.html 而後來看了module15的RequestContext和Context處理器的部分 在views.py中的comment回傳值部分嘗試的改成: return render(request,'comments.html', locals()) 也是同樣狀況 另外有一個重點是cmd方出現了一下訊息

UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.

以下是urls.py、views.py:

urls.py:

from django.conf.urls import url
from django.contrib import admin
from restaurants.views import menu,restaurants_list, comment
from views import welcome,meta
admin.autodiscover()
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^welcome/$',welcome),
    url(r'^meta/$',meta),
    url(r'^restaurants_list/$',restaurants_list),
   #url(r'^menu/(\d{1,5})/$',menu),
    url(r'^menu/$',menu),
    url(r'^comment/(\d{1,5})/$',comment),
]

views.py:

from django.shortcuts import render_to_response
from django.shortcuts import render
from django.http import HttpResponseRedirect
from restaurants.models import Restaurant, Food
from django.utils import timezone
from django.template import RequestContext
def comment(request, restaurant_id):
    if restaurant_id:
        r = Restaurant.objects.get(id=restaurant_id)
    else:
        return HttpResponseRedirect("/restaurants_list/")
    if request.POST:
        visitor = request.POST['visitor']
        content = request.POST['content']
        email = request.POST['email']
        date_time = timezone.localtime(timezone.now())
        Comment.objects.create(
            visitor=visitor,
            email=email,
            content=content,
            date_time=date_time,
            restaurant=r
        )
    return render_to_response('comments.html', RequestContext(request,locals()))
  #return render(request,'comments.html', locals())

`

myyang commented 8 years ago

@cj10243 我沒辦法重現你的問題,我使用render(...)能正常工作,可以請你提供一下你環境django和python版本?

由於我們寫書的時候是1.7版,所以介紹了render_to_response(),但官方文件在多次改版後表示將來可能會移除這個函式,所以請先不要使用

rhybs commented 8 years ago

您是指django和python的版本嗎? python: 2.7.12 django: 1.10

目前實測render_to_response()成功 而render()則出現驗證問題