decorate as_view() with extra context

Question:

I want to call class-based generic view with extra context from my method (view). Error that I get is as_view() takes exactly 1 argument (4 given) . I’m using django-userena.

Code that executes this is:

return userena_views.ProfileListView.as_view(request,template_name='userena/profil.html', extra_context=projekti)

In urls.py I have this line:

url(r'^accounts/(?P<username>[.w-]+)', userena_views.ProfileListView.as_view(template_name='userena/profil.html', extra_context=Projekat.objects.all), name='userena_profile_list'),

Why are these two different? What am I doing wrong?

Asked By: ivica

||

Answers:

this is due to how url functions. you can use kwargs to pass the parameters, and define a url pattern as follows:

url(r'^accounts/(?P<username>[.w-]+)', userena_views.ProfileListView.as_view(), name='userena_profile_list', kwargs={'template_name':'userena/profil.html', 'extra_context':Projekat.objects.all}),

EDIT

I misunderstood your question, sorry.
Then, trying to answer your question correctly… your code should be like this:

your_callable_view = userena_views.ProfileListView.as_view()
return your_callable_view(request, template_name='userena/profil.html', extra_context=projekti)

the reason is ProfileListView.as_view() returns a function that have to be called with parameters. url() do this for you, this is why it works in your ulrpatterns and not in your code. The only parameter as_view() is requiring is self.

Answered By: furins

Class based views can have extra context using the get_context_data(self, **kwargs) function. The extra context can be added in the definition of the Class under views.py instead of urls.py, which might be cleaner.

In the example below from the Django documentation, the DetailView context is appended to include ‘book_list’. The same method works for FormViews as well.

from django.views.generic import DetailView
from books.models import Book, Publisher

class PublisherDetailView(DetailView):

model = Publisher

def get_context_data(self, **kwargs):
    # Call the base implementation first to get a context
    context = super().get_context_data(**kwargs)
    # Add in a QuerySet of all the books
    context['book_list'] = Book.objects.all()
    return context
Answered By: George Gamblin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.