2015-01-20 93 views
0

我目前正在通過Django的官方教程,並且在嘗試瞭解泛型視圖如何實際工作時遇到問題。從官方文檔Django 1.7通用視圖

的源代碼:

class DetailView(generic.DetailView): 
    model = Question 
    template_name = 'polls/detail.html' 


class ResultsView(generic.DetailView): 
    model = Question 
    template_name = 'polls/results.html' 

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> 

results.html

<h1>{{ question.question_text }}</h1> 

<ul> 
{% for choice in question.choice_set.all %} 
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> 
{% endfor %} 
</ul> 

<a href="{% url 'polls:detail' question.id %}">Vote again?</a> 

現在,我明白ListViewDetailView是默認的通用視圖由Django提供。

如何DetailViewResultsView產生的detail.htmlresult.htmlquestion上下文變量?另外,DetailView生成的detail.html內的error_message上下文變量又如何?

回答

2

question對象以通用視圖的model屬性命名(在本例中爲Question)。詳細視圖自動包含這樣一個對象。

如果您問的是如何選擇特定的question對象,則默認情況下,詳細信息視圖必須傳遞來自URL的pk值,然後用該值查找該對象。從民調/ urls.py相關的代碼如下:

url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'), 

error_message,而另一方面,不包括在通用視圖。它僅在非通用視圖的示例中使用,因爲一個包括它在明確的背景:

return render(request, 'polls/detail.html', { 
    'question': p, 
    'error_message': "You didn't select a choice.", 
}) 
1

的DetailView有context_object_name參數,您可以使用模板來設置對象的名稱但如果不設置,則get_context_object_name方法做到這一點:

def get_context_object_name(self, obj): 
    """ 
    Get the name to use for the object. 
    """ 
    if self.context_object_name: 
     return self.context_object_name 
    elif isinstance(obj, models.Model): 
     return obj._meta.model_name 
    else: 
     return None 

它使用模型的名稱。然後SingleObjectMixinget_context_data將該標識符置於上下文中。無論如何,您還可以使用object標識符訪問該對象。

我確定你可以在Django文檔中閱讀所有這些內容,但有a nice page where you can explore class based views