[Answered ]-Django context variable names for the templates

1👍

You can change the question_list to something else by using the context_object_name this isn’t explained all that well in that part of the documentation, but …

Return the context variable name that will be used to contain the list
of data that this view is manipulating. If object_list is a queryset
of Django objects and context_object_name is not set, the context name
will be the model_name of the model that the queryset is composed
from, with postfix ‘_list’ appended. For example, the model Article
would have a context object named article_list.

is given under get_context_object_name method

This is what that method’s code looks like, It ought to clear up all doubts:

    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None
👤e4c5

1👍

I think this default context variable name only applies when dealing with Django’s Class Based Views.

E.g. If you are using a DetailView for a Animal model, Django will auto create a context variable called ‘animal’ for you to use in template. I think it also allows the use of ‘object’.

Another example is, as you mentioned, the ListView for a Animal model which would generate context name called animal_list.

However, in both of these cases, there are ways to change the default context variable name. If you specify ‘context_object_name’ in your DetailView, this will be the name you refer to in your template. This will also work for ListViews.

This website has all info on CBVs of all Django versions:

https://ccbv.co.uk/projects/Django/1.9/django.views.generic.detail/DetailView/

👤zubhav

Leave a comment