Generic detail view DetailView must be called with either an object pk or a slug in the URLconf.

This is my view: -

class DetailView(DetailView):
    template_name = "polls/detail.html"
    model = Question
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["question"] = self.get_object()
        return context

This is my detail.html:-

{% extends 'base.html' %}

{% block page_title %}{{question.question_text}}{% endblock page_title %}

{% block content %}
<div class="container mt-5 question">
    <form action={% url 'polls:vote' question.id %} method="post"> {% csrf_token %}
        <legend><h1 class="mb-3">{{question.question_text}}</h1></legend>
        {% for choice in question.choices.all %}
        <div class="form-check mx-4">
            <input class="form-check-input" type="radio" name="choice" id="choice{{forloop.counter}}" value={{choice.id}}>
            <label class="form-check-label fs-5" for="choice{{forloop.counter}}">{{choice.choice_text}}</label>
        </div>
        {% endfor %}
        <input class="btn btn-primary mt-4 mx-4" type="submit" value="Vote">
    </form>
    {% if error_message %}
        <p class="mt-4 mx-4">{{error_message}}</p>
    {% endif %}
</div>


{% endblock content %}

My urls.py: -

app_name = "polls"
urlpatterns = [
    path("", views.IndexView.as_view(), name="index"),
    path("<int:question_id>", views.DetailView.as_view(), name="detail"),
    path("<int:question_id>/results", views.results, name="results"),
    path("<int:question_id>/vote", views.vote, name="vote"),
]

I am getting this error: -

The specific error message is telling you what the issue is.

Note how the URLs are defined in the tutorial at Writing your first Django app, part 4 | Django documentation | Django

Your definition of the url is:

You have changed the name of the url parameter without making the other changes necessary to make this work.

(Also see Single object mixins | Django documentation | Django)

1 Like