Django gotcha: passing a request context
By NickI’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.
Share This
April 21st, 2009 at 10:39 am
I LOVE YOU!!!!!!!!!! i have been looking for this for 5 days. Thank you so much. I was having issues integrating the polls app that comes in the django intro tut so we can host contests. This was one hell of a bug. Great job!
=D
!!!context_instance=RequestContext(request))!!!
=D
March 6th, 2010 at 12:37 pm
Thanks for this post. I am new at django and this will be a big help.