Python Django邮政局
我试图让POST方法在pythondjango中工作。但是,CSRF实现无法成功 以下是我的观点。pyPython Django邮政局,python,django,Python,Django,我试图让POST方法在pythondjango中工作。但是,CSRF实现无法成功 以下是我的观点。py def showTime(request): t = get_template('FR/current_datetime.html') htmlContent = t.render(Context({"day_list": ['wednesday','thursday','friday'] , "current_date": datetime.datetime.no
def showTime(request):
t = get_template('FR/current_datetime.html')
htmlContent = t.render(Context({"day_list": ['wednesday','thursday','friday'] , "current_date": datetime.datetime.now()} ))
return HttpResponse(htmlContent)
def showWeekEnd(request):
c = {}
c.update(csrf(request))
if request.method == 'POST':
return render_to_response('EN/current_datetime.html', c)
我的URL模式是
url(r'^showTime/$', showTime),
url(r'^$', showTime),
url(r'^showWeekEnd/$', showWeekEnd),
我还启用了
MIDDLEWARE_CLASSES = (
'django.middleware.csrf.CsrfViewMiddleware',
)
我有(EN/current_datetime.html)
如果我必须传递更多的参数,当我启动应用程序时会遇到这个错误,并带有“发生服务器错误。请与管理员联系。”
请解释出现了什么问题?您是否尝试在render\u to\u响应中添加RequestContext(请求) views.py
from django.template import RequestContext
return render_to_response('EN/current_datetime.html', c, RequestContext(request))
这样做:
#settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
...,
'django.core.context_processors.csrf',)
在您看来,使用csrf装饰器而不是手动添加它
from django.views.decorators.csrf import csrf_protect
from django.template import RequestContext
@csrf_protect
def showWeekEnd(request):
c = RequestContext(request)
return render_to_response('EN/current_datetime.html', c)
这是什么<代码>c={};c、 更新(csrf(请求))是的,我也试过了。另外,我觉得它甚至没有出现在代码部分。在发布之前,尝试在GET请求中传递RequestContext。我注意到的另一件事是,我在启用“中间件类”中的“django.core.context_processors.csrf”时出现了这个错误。“django.MIDDLEWARE.csrf.CsrfViewMiddleware”应该在中间件类中,而不是“django.core.context_processors.csrf”。可能您在views.py中导入了错误的csrf,应该是“from django.core.context_processors import csrf”。是的,解决了最初的问题。谢谢。我将尝试让其余的处理器正常工作。谢谢!!我注意到了一个问题,我刚刚在“中”注释了“django.middleware.csrf.CsrfViewMiddleware”MIDDLEWARE_CLASSES“并尝试了相同的代码,但仍然有效。那么CSRF令牌是如何处理的?@Burhan Khalid我找到了原因。如果我评论django.MIDDLEWARE.CSRF.CsrfViewMiddleware,则不会进行任何验证。谢谢!!
from django.shortcuts import render
import datetime
def showWeekEnd(request):
if request.method == 'POST':
return render(request, 'EN/current_datetime.html')
def showTime(request):
c = {}
c["day_list"] = ['wednesday','thursday','friday']
c["current_date"] = datetime.datetime.now()
return render(request, 'FR/current_datetime.html', c)
#settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
...,
'django.core.context_processors.csrf',)
from django.views.decorators.csrf import csrf_protect
from django.template import RequestContext
@csrf_protect
def showWeekEnd(request):
c = RequestContext(request)
return render_to_response('EN/current_datetime.html', c)