1

I try to dynamically call a view in Django with this url configuration :

url(r'^niveau/(?P<niveau_id>\d+)/(?P<channel>\w+)/$', views.switcher , name='vue_niveau')

Then in my view.py, i have :

def switcher(request, niveau_id, channel):
if channel == 'VueNiveau':
    return VueNiveau.as_view()(request)

It works, as i get the good view call, but then when i try to get the niveau_id in my VueNiveau context :

class VueNiveau(generic.TemplateView):
template_name = 'cours/vue_niveau.html'
...

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    niveau = Niveau.objects.get(id=kwargs['niveau_id'])
    context['niveau'] = niveau

i get a KeyError, saying that niveau_id is undefined...

Without the switcher function, all works perfectly and i can get the url data etc... So it seems like something is happening between the call of the switcher function and get_context_data...

Does someone understand this behaviour ?

Nnomuas
  • 63
  • 5

1 Answers1

3

You need to pass the URL parameters as named parameters to the view function as well:

def switcher(request, niveau_id, channel):
    if channel == 'VueNiveau':
        return VueNiveau.as_view()(request, niveau_id=niveau_id, channel=channel)
    # …

That being said, it might be better to add a special URL pattern:

urlpatterns = [
    url(
        r'^niveau/(?P<niveau_id>\d+)/vueNiveau/$',
        views.VueNiveau.as_view(),
        name='vue_niveau'
    ),
    url(
        r'^niveau/(?P<niveau_id>\d+)/(?P<channel>\w+)/$',
        views.switcher,
        name='vue_niveau'
    )
]
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Wow thank you so much ! :D I don't get the point with "it might be better to add a special URL pattern" ? It wouldn't be dynamic anymore ? My aim is to build only one url for several complex exercises which would need totally different and rich contexts... – Nnomuas Jul 05 '20 at 21:55
  • @Nnomuas: but if `channel == 'vueNiveau'`, then that part is not dynamic. So you can move it to a static URL part. – Willem Van Onsem Jul 05 '20 at 22:04
  • Yes you're right, i was juste doing some tests ^^. Next step is to make it work for all of my views without having to precise things in this way. :) The main issue was how to keep the url data, so thank you again for your super fast answer ;). – Nnomuas Jul 05 '20 at 22:07