django - 如何在 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
解决方案
您可以使用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})
推荐阅读
- python - 具有嵌套循环的python中函数的时间复杂度
- c# - 单个表中的多个一对多关系
- django - 将字段添加到 Django 模型
- python-3.x - 从 nseindia.com 获取数据后如何为丢失的数据添加空白
- java - 如何从服务更新 UI?
- javascript - API post call 的输出响应 - Javascript - 400 Bad Request
- python - PyCharm 是否能够根据 `.python-version` 文件自动选择解释器?
- mysql - 为什么在 MySQL 5.6 中为表添加索引会导致死锁?
- java - 并非所有口味 CodeChef DSA 学习第 2 周
- c# - Azure Blob 上大文件的 PGP 加密