在Django模板中访问RequestContext?

时间:2012-09-13 02:27:53

标签: django django-templates django-generic-views django-context

我似乎无法访问django模板中的请求对象。

这是我的settings.py文件的一部分:

import django.conf.global_settings as DEFAULT_SETTINGS
TEMPLATE_CONTEXT_PROCESSOR = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
    'django.core.context_processors.request',
)

urls.py

urlpatterns = patterns('',
    url(r'^event/create/$', EventCreateView.as_view(), name='create_event'),
    url(r'^event/update/(?P<pk>\d+)/$', EventUpdateView.as_view(), name='update_event'),
    url(r'^event/delete/(?P<pk>\d+)/$', EventDeleteView.as_view(), name='delete_event'),
)

views.py

from django.views.generic import CreateView, UpdateView, DeleteView
from events.models import Event
from events.forms import EventForm

class EventCreateView(CreateView):
    model = Event
    form_class = EventForm

class EventUpdateView(UpdateView):
    model = Event
    form_class = EventForm

class EventDeleteView(DeleteView):
    model = Event

forms.py

from django.forms import ModelForm
from events.models import Event

class EventForm(ModelForm):
    class Meta:
        model = Event

event_form.html(适用于CreateView / UpdateView)

{% block content %}
    <form action='{{ request.get_full_path }}' method='post'>
        {% csrf_token %}
        <table>
            {{ form.as_table }}
        </table>
        <input type='submit' value='Create event!' />
    </form>
{% endblock %}

上面,request.session似乎什么都不做。我已经尝试过查看文档和类似的问题,但似乎没有任何工作。有什么想法吗?

提前致谢。

2 个答案:

答案 0 :(得分:3)

你有一个错字,在TEMPLATE_CONTEXT_PROCESSORS结束时缺少'S',也许就在你的问题中?设置应该是:

TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
 "django.core.context_processors.debug",
 "django.core.context_processors.i18n",
 "django.core.context_processors.media",
 "django.core.context_processors.static",
 "django.core.context_processors.tz",
 "django.contrib.messages.context_processors.messages",
 "django.core.context_processors.request",)

,而不是TEMPLATE_CONTEXT_PROCESSOR = ...。我更喜欢完全覆盖设置,因此很清楚什么是活动的(例如,您可能希望在生产中禁用调试)。

答案 1 :(得分:1)

您使用Django的Session框架吗?然后是的,request.session将什么都不做,因为a会话是类似dict的对象而模板引擎不知道如何呈现它。