我只是一个初学者,从网上的一些教程开始,我无法理解为什么这对我不起作用:
my views.py
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.core.context_processors import csrf
class MainPage(View):
def get(self, request):
return render_to_response("helloworld.html")
class TestHandler(View):
def post(self, request):
q = {}
q.update(csrf(request))
#return render_to_response('test.html', q)
return render_to_response('test.html', {'q':q}, context_instance=RequestContext(self.request))
def get(self, request):
q = self.request.GET.get('q')
return HttpResponse(q)
和我的urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from views import MainPage, TestHandler
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^hello$', MainPage.as_view(), name='home'),
url(r'^testform/', TestHandler.as_view()),
url(r'^admin/', include(admin.site.urls)),
的helloworld.html
>->-<html>
>->->-<head>
>->->->-<title>Hello, World!</title>
>->->-</head>
>->->-<body>
>->->->-<form method="post" action="/testform/" >
{% csrf_token %}
>->->-<input name="q">
<input type="submit">
</form>
>->->-</body>
>->-</html>
的test.html
>-<body>
>-Hello {{q}}
>-</body>
这是在django 1.6上运行的,我阅读了大部分帖子但仍然无法弄明白。
答案 0 :(得分:1)
不幸的是,你粘贴的东西有点混乱,你使用的是基于类的视图,但是你已经将它们与基于函数的视图混合在一起(也缺少了一半的声明)。
在settings.py中启用CSRF Middlware
MIDDLEWARE_CLASSES = (
...
'django.middleware.csrf.CsrfViewMiddleware',
...
)
将您的观点修复为正确的基于类的视图,您粘贴的内容完全错误:
from django.views.generic import CreateView, TemplateView
from django.core.urlresolvers import reverse_lazy
# Create the form in your forms.py
from .forms import (
MyTestForm,
)
class MainPage(TemplateView):
template_name = "test.html"
class TestHandler(CreateView):
form_class = MyTestForm
template_name = "helloworld.html"
success_url = reverse_lazy('home')
创建表单模板:
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<form method="post" action="/testform/">
{% csrf_token %}
<input name="q">
<input type="submit">
</form>
</body>
</html>