'Create a Django detail def
well these are the codes:
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from . import models
def detail(request, question_id):
question = get_object_or_404(models.Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
detail.html
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
urls.py
from django.urls import path
from . import views
from django.urls import path, re_path
path(r'^(?P<pk>[0-9]+)/$', views.detail, name='detail'),
but the result is an TypeError : detail() got an unexpected keyword argument 'pk'
and if you add 'pk' argument to detail() like this :
def detail(request, pk, question_id):
question = get_object_or_404(models.Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
the resualt is another error : detail() needs an important argument 'question_id'
where is the problem from?
Solution 1:[1]
You're using two different names for the same thing: pk in your URL and question_id in your view function. Django has no way to know they're supposed to be the same thing.
Change the name of the parameter in your route to question_id so it matches your view function:
path(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
Or you could rename the function parameter to pk to match your existing URL, but question_id is probably a better name since it's more descriptive.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chris |
