0leg
0leg

Reputation: 14134

Django get_context_data() variable gets overwritten somewhere

This is simplified code example, but may be someone knows the reason the problem occurs without the exact copy of the code. So:

class FooView(TemplateView):
  template_name = 'foo.html'

  def get_context_data(self, **kwargs)
    context = super(FooView, self).get_context_data(**kwargs)
    ...
    # here we get link to domain
    ...
    args = {'domain': domain}
    context.update(args)

    import pdb; pdb.set_trace() # here 'domain' has a value
    return context

The html template foo.html tries to access the 'domain' value with {{ domain }}, but it is None.

This happens only if I use 'domain' as the label. So if I change domain to domain1 or foo - it works.

How is this possible? Is it possible domain name gots overwritten somehow, maybe some has a clue?

EDIT Change get_context_view --> get_context_data (mistype)

EDIT2 My 'domain' context variable gets ovewritten by context_processor. All worked fine when function-based views were used. After switching to class-based views - the 'domain' started to get overwritten. May be get_context_data() is not strong enough? Is there any way to prevent context processor from overwriting the variable?

Upvotes: 1

Views: 688

Answers (2)

Tom
Tom

Reputation: 5835

The TemplateView returns a TemplateResponse which is known to overwrite the context passed to it with data from context processors. This is something that's changing in Django 1.8 to be more consistent with render.

You should be able to fix this by overwriting render_to_response on your view with something like:

from django.shortcuts import render

...

class FooView(TemplateView):
    def render_to_response(self, context, **response_kwargs):
        return render(self.request, self.get_template_names()[0], context)

Upvotes: 1

catavaran
catavaran

Reputation: 45575

Yes, it is possible if some or template tags of context processors injects domain variable into context.

Are you sure than method is called get_context_view? Imho it should be get_context_data.

Upvotes: 2

Related Questions