2013-05-13 46 views
0

我是一個django新手,並希望將Singly整合到django投票應用程序中。我已經使用基於類的視圖來允許來自單一應用程序的模型隨着民意調查模型一起傳遞。Django模板不能正確使用基於類的視圖呈現

問題是,即使數據存在於數據庫中,我也無法從Singly模型獲取數據。

現在我只想顯示用戶配置文件的access_token和配置文件ID。

這裏是我的Views.py代碼:(僅在問題視圖)

class IndexView(ListView): 
    context_object_name='latest_poll_list' 
    queryset=Poll.objects.filter(pub_date__lte=timezone.now) \ 
      .order_by('-pub_date')[:5] 
    template_name='polls/index.html' 

    def get_context_data(self, **kwargs): 
     context = super(IndexView, self).get_context_data(**kwargs) 
     context['user_profile'] = UserProfile.objects.all() 
     return context 

這是我的urls.py:

urlpatterns = patterns('', 
    url(r'^$', 
     IndexView.as_view(), 
     name='index'), 
    url(r'^(?P<pk>\d+)/$', 
     DetailView.as_view(
      queryset=Poll.objects.filter(pub_date__lte=timezone.now), 
      model=Poll, 
      template_name='polls/details.html'), 
     name='detail'), 
    url(r'^(?P<pk>\d+)/results/$', 
     DetailView.as_view(
      queryset=Poll.objects.filter(pub_date__lte=timezone.now), 
      model=Poll, 
      template_name='polls/results.html'), 
     name='results'), 
    url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote', name='vote'), 
) 

這裏是我的index.html:

{% load staticfiles %} 
<h1>Polls Application</h1> 

<h2>Profile Info:</h2> 

    <div id="access-token-wrapper"> 
     <p>Here's your access token for making API calls directly: <input type="text" id="access-token" value="{{ user_profile.access_token }}" /></p> 
     <p>Profiles: <input type="text" id="access-token" value="{{ user_profile.profiles }}" /></p> 
    </div> 

<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" /> 

{% if latest_poll_list %} 
    <ul> 
    {% for poll in latest_poll_list %} 
     <li><a href="{% url 'polls:detail' poll.id %}">{{ poll.question }}</a></li> 
    {% endfor %} 
    </ul> 
{% else %} 
    <p>No polls are available.</p> 
{% endif %} 

它能夠正確地獲取民意調查,但它並沒有在任何文本框中顯示任何信息,即該user_profile.access_token和user_prof ile.profiles。

我認爲問題是模板的渲染不正確。它應該傳遞上下文'user_profile',但不是。或者由於某種原因,它不從數據庫中獲取數據,因爲UserProfile數據庫中有一個條目。

我會很感激你的幫助,人。

回答

0

user_profile上下文變量包含UserProfile對象的列表。從代碼:

context['user_profile'] = UserProfile.objects.all() # will return a QuerySet, that behaves as list 

而且在模板訪問它,就好像它是一個單獨的對象:

{{ user_profile.access_token }} 
{{ user_profile.profiles }} 

所以要麼把這個變量單用戶配置對象的視圖。例如:

if self.request.user.is_authenticated() 
    context['user_profile'] = UserProfile.objects.get(user=self.request.user) 
else: 
    # Do something for unregistered user 

無論是遍歷配置文件模板:

{% for up in user_profile %} 
    {{ up.access_token }} 
{% endfor %} 

無論是訪問由指數模板簡介:

{{ user_profile.0.access_token }} 
+0

哈哈。謝啦。它總是那些我們忘記的小事情回來困擾着我們。 – 2013-05-13 07:26:04

相關問題