Joshua Kravitz
Joshua Kravitz

Reputation: 2865

Access to RequestContext in Django template?

I don't seem to have access to the request object in my django templates.

Here's part of my settings.py file:

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 (for 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 %}

Above, request.session seems to do nothing. I've tried looking at the docs and at similar problems, but nothing seems to work. Any ideas?

Thanks in advance.

Upvotes: 3

Views: 2756

Answers (2)

Steven
Steven

Reputation: 2698

You have a typo, a missing 'S' at the end of TEMPLATE_CONTEXT_PROCESSORS, perhaps just in your question? Setting should be:

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",)

, not TEMPLATE_CONTEXT_PROCESSOR = .... I prefer to override the setting entirely so it's clear what's active (you might want to disable debug in production, for instance).

Upvotes: 3

Torsten Engelbrecht
Torsten Engelbrecht

Reputation: 13496

Do you use the Django's Session framework? Then yes, request.session will do nothing, since the a session is a dict-like object and the template engine does not know how to render it.

Upvotes: 1

Related Questions