views.py:
def index(request): return render_to_response('index.html', {}) def photos(request, artist): if not artist: return render_to_response('photos.html', {'error' : 'no artist supplied'}) photos = get_photos_for_artist(artist) if not photos: logging.error('Issue while getting photos for artist') return render_to_response('photos.html', {'error': 'no matching artist found'}) return render_to_response('photos.html', {'photos': photos})
index.html的:
{% block content %}{% endblock %}find artist photos {% block error %} {% endblock %}
photos.html:
{% extends 'index.html' %} {% block error %} {% if error %}{{ error}}
{% endif %} {% endblock %} {% block content %} {% if photos %} {% for photo in photos %} {{ photo }} {% endfor %} {% endif %} {% endblock%}
url.py:
urlpatterns = patterns('', (r'', index), (r'^time/$', current_datetime), (r'^photos/(\w+)$', photos) )
我甚至尝试添加{% csrf_token %}
,但没有运气
谢谢
更新
我在日志中看到了这些
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. warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.")
将context_instance = RequestContext(request)**添加到render_to_response()**之后
添加context_instance=RequestContext(request)
到您将在其中使用表单的每个视图:
return render_to_response('index.html', {}, context_instance=RequestContext(request) ) return render_to_response('photos.html', {'photos': photos}, context_instance=RequestContext(request) )
假设您使用的是相当新版本的Django(1.3/1.4/dev),您应该按照以下步骤操作:
在settings.py
,将中间件添加django.middleware.csrf.CsrfViewMiddleware
到
MIDDLEWARE_CLASSES
列表中.
在模板中,使用{% crsf_token %}
表单中的内容.
在您的视图中,确保django.core.context_processors.csrf
通过以下方式使用上下文处理器:
使用RequestContext
来自django.template
直接从中导入csrf处理器 from django.core.context_processors
from django.template import RequestContext from django.shortcuts import render_to_response def my_view(request): return render_to_response('my_template.html', {}, context_instance=RequestContext(request))
要么
from django.core.context_processors import csrf from django.shortcuts import render_to_response def my_view(request): c = {csrf(request)} return render_to_response('my_template.html', c)
Django 1.3中的csrf或Django 1.4中的csrf
Django 1.3中的 RequestContext或Django 1.4中的RequestContext
(后人和未来观众的详尽帖子)