Django--仅为当前用户

时间:2017-06-09 19:06:55

标签: django django-models django-templates django-views

首先,我知道有很多关于在模板中访问模型的问题,但让我解释为什么这是不同的。

我想要用户可以查看其详细信息的个人资料页面。我能做到这一点,但有一个小虫子。如果有3个用户(比如A,B,C),并且用户A想要查看他的个人资料,他会看到三次。像这样:

like this

如何在一次迭代后停止循环,以便用户只获取一次他的个人资料信息。

这是我的网址:

url(r'^profile/$', views.IndexView.as_view(), name='profile'),

Views.py:

class IndexView(generic.ListView):
template_name = 'profile.html'

def get_queryset(self):
    return Profile.objects.all()

和profile.html:

{% if user.is_authenticated %}
{% for profile in object_list %}
<h1>{{ request.user }}'s Profile</h1>
<table>
<tr>
    <td>Username:</td>
    <td>{{ user.username }}</td>
</tr>
<tr>
    <td>First Name:</td>
    <td>{{ user.first_name }}</td>
</tr>
<tr>
    <td>Last Name:</td>
    <td>{{ user.last_name }}</td>
</tr>
<tr>
    <td>Email:</td>
    <td>{{ user.email }}</td>
</tr>
<tr>
    <td>Personal Info:</td>
    <td>{{ user.profile.personal_info }}</td>
</tr>
<tr>
    <td>Job Title:</td>
    <td>{{ user.profile.job_title }}</td>
</tr>
<tr>
    <td>Department:</td>
    <td>{{ user.profile.department }}</td>
</tr>
<tr>
    <td>Location:</td>
    <td>{{ user.profile.location }}</td>
</tr>
<tr>
    <td>Expertise:</td>
    <td>{{ user.profile.expertise }}</td>
</tr>
<tr>
    <td>Phone Number:</td>
    <td>{{ user.profile.phone_number }}</td>
</tr>
<tr>
    <td>Contact Skype:</td>
    <td>{{ user.contact_skype }}</td>
</tr>
<tr>
    <td>Contact Facebook:</td>
    <td>{{ user.contact_facebook }}</td>
</tr>
<tr>
    <td>Contact Linkedin:</td>
    <td>{{ user.profile.contact_linkedin }}</td>
</tr>
</table>

<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {% include 'form-template.html' %}
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <a href={%  url 'profile_edit' %}><input type="button" class = " col-sm-offset-2 btn bk-bs-btn-warning " name="cancel" value="Edit" /></a>
            </div>
        </div>
</form>
{% endfor %}
{% else %}
    <h2>Please login to see your Profile</h2>
{% endif %}

我是django的新手,谢谢你的进步。

1 个答案:

答案 0 :(得分:1)

您循环播放所有个人资料但未在循环中实际使用此数据,而是使用user.profile

这意味着您可能在数据库中有3个Profile对象,然后为每个对象显示当前用户的详细信息,这是不可取的。

因此,您可以完全删除循环,并保留其引用所有user.profile属性的内容以实现所需的结果。

修改

默认情况下,user似乎会传递到您的模板中,并指向当前登录的用户。所以user.profile将返回配置文件,这样做无需做任何其他事情。所以user.profile.personal_info是有效的,应该可行。当您尝试直接使用profile时,这不是一回事,并且未定义,因此profile.personal_info无法正常工作。然后在循环中使用profile循环遍历Profile对象,但这不是必需的或已被使用。希望这是有道理的。