What is this? From this page you can use the Social Web links to save Django gotcha: passing a request context to a social bookmarking site, or the E-mail form to send a link via e-mail.

Social Web

E-mail

E-mail It
March 31, 2009

Django gotcha: passing a request context

Posted in: python, django, pinax

I’m playing with django and pinax lately and I find it a very pleasant experience so far.

I did spend some time on a stupid little thingy that I will now never forget ;) I created my first 2 views, both generic views, which worked fine, but then I did my first manual view. In my template code, I had something like:

1
2
3
4
5
    {% if user.is_authenticated %}
        //stuff here
    {% else %}
        
    {% endif %}

I was using this in my generic views as well (through template extension), but this time, I got a crash. Turns out that in order to have access to the user object, I need to pass in a special context, a RequestContext. Generic views do that automagically, but with manually written views, this passing along needs to be done explicitly. So, in your view, you need something like (the magic is on line 9):

1
2
3
4
5
6
7
8
9
10
11
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
 
 
def view_name(request, my_object_id):
    my_model = get_object_or_404(MyModel, pk=my_object_id)
    if request.method == "GET":
        return render_to_response('path/to/new_my_model.html', {'my_model' : my_model, 'form': MyModelForm()}, context_instance=RequestContext(request)
    #rest of the view code here...
new_idea = login_required(new_idea)

Hope this helps.


Return to: Django gotcha: passing a request context