首页 > 解决方案 > 如何在 Django 中查看登录用户以外的用户信息?

问题描述

我正在使用 Django 2.2 和 PostgreSQL。登录后,用户有一个页面,他们可以在其中查看其他用户的信息。但是,所有用户的登录信息都会显示在页面上。我想查看除他之外的其他用户的信息。我怎样才能做到这一点?

模板/neighbor.html

{% csrf_token %}
{% if neighbor_list %}
{% for neighbor in neighbor_list %}
<div class="card border-left-success  py-2" style="background-color:    rgb(240,240,240);">
  <div class="card-body">
    <div class="row no-gutters align-items-center">
      <div class="col mr-2">
         <div class="text-left">
            <strong><p><a href="{% url 'store:neighbor_detail' neighbor.user.username %}">{{neighbor.user.first_name}} {{neighbor.user.last_name}}</a></p></strong>
             <p><strong><i class="fa fa-user"> : </i></strong>{{neighbor.user.username}}</p>
             <p><strong><i class="fa fa-envelope"> : </i></strong>{{neighbor.user.email}}</p>
              <p><strong><i class="fa fa-phone"> : </i></strong>{{neighbor.phone}}</p>
              <p><strong><i class="fa fa-fax"> : </i></strong>{{neighbor.fax}}</p>
              {% if neighbor %}
              <p><strong><i class="fa fa-map"> : </i></strong>{{neighbor.neighborhood}}, {{neighbor.avenue}}, {{neighbor.street}}, {{neighbor.block}}, No.{{neighbor.number}}, Kat.{{neighbor.storey}}, {{neighbor.district}}/{{neighbor.province}}</p>
              <p>{{neighbor.profile_image}}</p>
              {% endif %}
       </div>
     </div>
   </div>
 </div>
</div>
{% endfor %}
{% endif %}

商店/views.py

from store.models import StoreOtherInfo
def neighbor(request):

    neighbor_list = StoreOtherInfo.objects.all()
    return render(request,'store/neighbor.html',{"neighbor_list":neighbor_list"}

商店/models.py

class StoreOtherInfo(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE,blank=True, null=True)
    phone = models.CharField(max_length=11)
    fax = models.CharField(max_length=11)
    province = models.CharField(max_length=11)
    district = models.CharField(max_length=11)
    neighborhood = models.CharField(max_length=11)
    ...

def __str__(self):
    return self.user.username

标签: djangotemplates

解决方案


您可以使用exclude(user=request.user).

from django.contrib.auth.decorators import login_required

@login_required
def neighbor(request):
    neighbor_list = StoreOtherInfo.objects.all().exclude(user=request.user)
    return render(request,'store/neighbor.html',{"neighbor_list":neighbor_list})

在上面的代码中,我使用login_required装饰器来确保用户已登录。另一种方法是检查user.is_authenticated并且仅exclude()在用户登录时执行。

@login_required
def neighbor(request):
    neighbor_list = StoreOtherInfo.objects.all()
    if request.user.is_authenticated:
        neighbor_list = neighbor_list.exclude(user=request.user)
    return render(request,'store/neighbor.html',{"neighbor_list":neighbor_list})

推荐阅读