Passing URL arguments to a Class View?

Parts of the URL can be passed to a function View as such:

urls.py:

urlpatterns = [
path(‘<int:question_id>/vote/’, views.vote, name=‘vote’),
]

views.py:

def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST[‘choice’])

(taken from the polls tutorial)

How can a URL parameter such as “question_id” be passed to a class View?

urls.py:

urlpatterns = [
path(‘<int:question_id>/vote/’, DetailView.as_view(), name=‘vote’),
]

See Built-in class-based generic views | Django documentation | Django, especially the examples.

1 Like

Thank you for the source. It turns out I can call self.kwargs to get these values in get_queryset() (as in the example you pointed me) but I cannot do that in get_context_data or in the __init__ methods. E.g. the next code gives an error 'TrackDetailView' object has no attribute 'kwargs'

class TrackDetailView(generic.UpdateView):
template_name = ‘track/snippets/mainlist/detail.html’

def __init__(self, **kwargs):
    super().__init__(**kwargs)
    print(self.kwargs)  # <-------------ERROR, DOES NOT EXIST

def get_queryset(self):
    model = eval(self.kwargs['model'].title().replace('_', ''))  # <-------WORKS FINE
    self.fields = model.LIST_COLDATA
    return model.objects

Also this works but prints an empty dictionary - {}.

class TrackDetailView(generic.UpdateView):
template_name = ‘track/snippets/mainlist/detail.html’

def __init__(self, **kwargs):
    super().__init__(**kwargs)
    print(kwargs)  # <------------------PRINTS EMPTY DICTIONARY

def get_queryset(self):
    model = eval(self.kwargs['model'].title().replace('_', ''))  # <-------WORKS FINE
    self.fields = model.LIST_COLDATA
    return model.objects

What am I missing? Where can I read more on this?

You would want to follow the “flow” of execution of a CBV.

I suggest you read the actual source code for the Django-provided CBVs to see how they work.

Additionally, I recommend:

Both of these sites will help you understand what happens within the Django-provided CBVs.

1 Like

Thank you so much! The flow is indeed very obscure to me atm. Imma get to work on these