Read request variable in template tag

1.9k Views Asked by At

I am in the process of turning a Django project into a multi-language site. For that purpose I am trying to adopt the countries-for-django (github) package.

In one of the templatetags, the code is trying to read the session variable django_country (taken from here), but Django 1.5 trips over reading the request variable from the context.

Exception Type: AttributeError 
Exception Value: 'NoneType' object has no attribute 'session'

The code in the template tag is as stated below (the code has been extended since the first post):

class GetCurrentCountryNode(Node):
    def __init__(self, variable):
        self.variable = variable

    def get_current_country(self, context):
        from django.template import Context
        return context.get('request').session.get('django_country')

    def render(self, context):
        context[self.variable] = self.get_current_country(context)
        return ''

...

@register.tag("get_current_country")
def do_get_current_country(parser, token):
    args = token.contents.split()
    if len(args) != 3 or args[1] != 'as':
        raise TemplateSyntaxError("'get_current_country' requires 'as variable' (got %r)" % args)
    return GetCurrentCountryNode(args[2])

When I print the context variable, the print out does not contain any request variable. However, I can see via the Django Toolbar that the variable is existing.

Did the way of reading the context variable change with Django 1.5? I could not find anything in the documentation.

Views.py and template added for completeness.

views.py

...
class StartView(FormView):
    form_class = StartForm
    template_name = 'home.html'

    def form_valid(self, form):
        self.request.session['address'] = form.cleaned_data['address']
        return HttpResponseRedirect(reverse_lazy('new'))
...

home.html

{% load countries %}    
{% get_current_country as country %}
{% get_available_countries as COUNTRIES %}

<head>
... 
1

There are 1 best solutions below

0
On

The code works if django.core.context_processors.request is added to the TEMPLATE_CONTEXT_PROCESSORS in the settings.py.