0

私は django 初心者で、Singly を django Polls アプリケーションに統合したいと考えていました。クラス ベースのビューを使用して、単独アプリのモデルを Polls モデルと共に渡すことができるようにしました。

問題は、データベース内にデータが存在する場合でも、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_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 に答える