ivica
ivica

Reputation: 1428

decorate as_view() with extra context

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?

Upvotes: 3

Views: 1198

Answers (2)

George Gamblin
George Gamblin

Reputation: 33

Class based views can provide extra context data via a get_context_data method.

In the example below from the Django documentation, book_list is added to the DetailView context. 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 context
        context = super().get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        context['book_list'] = Book.objects.all()
        return context

Upvotes: 1

furins
furins

Reputation: 5048

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.

Upvotes: 3

Related Questions