简体   繁体   中英

Django about get_context_data()

I was looking in django source-code to understand super(ExampleView, self).get_context_data(**kwargs) and why I used it in my view:

class ExampleView(TemplateView):
    # ... atributes

    def get_context_data(self, **kwargs):
        context = super(ExampleView, self).get_context_data(**kwargs)
        context['key'] = 'value'

        return context

I've found:

class ContextMixin(object):
    """
    A default context mixin that passes the keyword arguments received by
    get_context_data as the template context.
    """

    def get_context_data(self, **kwargs):
        if 'view' not in kwargs:
            kwargs['view'] = self
        return kwargs

I can't figure it out what that condition or kwargs['view'] = self does.

I've tried in my view to overwrite get_context_data() without that default condition:

class ExampleView(TemplateView):
    # .. atributes

    def get_context_data(self, **kwargs):
        kwargs['key'] = 'value'

        return kwargs

and it worked the same as the first code I've written.

Those 2 lines of code add the view as variable to the context if it was not already present. Most people never use this, but you could do something like this:

class SomeView(TemplateView):
    template_name = "something.html"
    title = "My list of books"

    def books(self):       #custom method
        return Book.objects.all()

And then in your template you could reference the books method and title attribute through the view variable:

<h1>{{ view.title }}</h1>
<ul>
  {% for book in view.books %}
    <li>{{ book }}</li>
  {% enfor %}
<ul>

Ah yes, and note that you don't even need a custom get_context_data() method in this case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM