0

我是 django 新手,想将 Singlely 集成到 django Polls 应用程序中。我已经使用基于类的视图来允许来自单个应用程序的模型与投票模型一起传递。

问题是,即使数据库中存在数据,我也无法从 Single 模型中获取数据。

现在我只想显示用户配置文件的 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_profile.profiles。

我认为问题在于模板的不正确渲染。它应该传递上下文'user_profile',但不是。或者由于某种原因,它没有从数据库中获取数据,因为 UserProfile 数据库中有一个条目。

我会很感激你的帮助,人们。

4

1 回答 1

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 }}

因此,要么在视图中将单个 UserProfile 对象放入此变量。例如:

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 }}
于 2013-05-13T07:20:56.520 回答