Class-based Django presentation example: where does ** kwargs come from?

In the examples, I constantly see that ** kwargs went around without mentioning where it was coming from:

from django.views.generic import DetailView from books.models import Publisher, Book class PublisherDetailView(DetailView): context_object_name = "publisher" model = Publisher def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(PublisherDetailView, self).get_context_data(**kwargs) # Add in a QuerySet of all the books context['book_list'] = Book.objects.all() return context 

Where are ** kwargs magically torn out?

Also, doesn't this seem like more than just adding a single dictionary object?

+7
source share
2 answers

Look at the basic implementation of SingleObjectMixin ("original" get_context_data ).

It simply returns **kwargs as a context (dictionary), adding an editable object with the specified key.

  def get_context_data(self, **kwargs): context = kwargs context_object_name = self.get_context_object_name(self.object) if context_object_name: context[context_object_name] = self.object return context 

In DetailView , quarts are “magically plucked” from what they call it / passes in these quarts. In your case, it will be BaseDetailView.get() .

 class BaseDetailView(SingleObjectMixin, View): def get(self, request, **kwargs): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) 

Subsequently, it is used by many presentation classes (as in render_to_response(self.get_context_data) ), which passes the original context dictionary to self.response_class , which by default is django.template.TemplateResponse .

TemplateResponse knows how to make itself, and in its resolve_context function, finally converts the dictionary into django.template.Context

You really can completely track the source path from the source method to the end.

+5
source

Squares are generated in URLConf . For example, this will populate the pk element:

 urlpatterns = patterns('', (r'^authors/(?P<pk>\d+)/$', AuthorDetailView.as_view()), ) 

The call is made through view in View.as_view , and then through View.dispatch , which calls TemplateView.get .

+5
source

All Articles