Reputation: 71
It involves generic views, specifically the DetailView
and it's explanation in the Django tutorial part 4.
My urls looks like this:
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),)
My views looks like this:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from polls.models import Choice, Question
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
... # same as above
This is all from the tutorial btw. Let's look at my detail.html template:
<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>
How does my detail template know that the question variable (as in, question.question_text
) refers to my Question
model? I've never declared it, and the model name begins with a capital letter.
The tutorial says, "For DetailView the question variable is provided automatically – since we’re using a Django model (Question), Django is able to determine an appropriate name for the context variable."
How does it do that? If I go in and capitalize the variable, it doesn't work anymore. Where is DetailView
getting this variable from?
Upvotes: 2
Views: 889
Reputation: 254
question == object Basically, the content type set for the model Question is question. A full content type lookup is performed on the Model you specify from the App Name and Model name (i.e.. question__question)
This also works well for Django's Generic relations where you can specify the model name in your lookups instead of first acquiring the content type.
Upvotes: 0
Reputation: 45595
This data is available in the model's meta information. You can get it in your code too:
>>> Question._meta.model_name
'question'
Upvotes: 1