logicOnAbstractions
logicOnAbstractions

Reputation: 2580

CreateView not receiving Kwargs from urls.py

I've been using arguments provided in the path(...) in urls.py for my view, which is a TemplateView.

Now, I've been trying to do the same with a similar template, but using a CreateView. After some debugging, I've realized that for some reason a CreateView doesn't seem to receive the kwargs defined in the urls.py path. For instance:

urls.py

path('product/<int:pk>/', views.SomeViewClass.as_view(), {"foo": "bar"}, name='detail_product', ),

views.py

class SomeViewClass(TemplateView):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        section = kwargs["foo"]

The above works. However, this doesn't:

urls.py

path('create/', views.OtherClassView.as_view(), {"foo": "bar"}, name='create'),

views.py

class OtherClassView(CreateView):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        section = kwargs["foo"]

Any obvious workaround? Other than fishing out this parameter through a completely different pipeline?

Upvotes: 2

Views: 412

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476729

The .get_context_data(…) method [Django-doc] indeed does not receive the URL parameters, in that case the **kwargs are a dictionary of items that need to be included in the context.

You can work with self.kwargs to access the URL parameters:

class SomeViewClass(TemplateView):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        section = self.kwargs['foo']

Upvotes: 3

Related Questions