python - 显示所有将其国家设置为与 request.user 相同的用户
问题描述
我正在构建一个 BlogApp,我试图向所有将其设置Countries
为request.user
.
例如:如果
user_1
是request.user
和选中的州选择Victoria
和国家Australia
然后user_2
注册并设置相同的州Victoria
和国家Australia
。
所以我想显示所有将其设置为相同的用户,Country
但是state
当request.user
我访问这些类型的用户时,它只是显示所有用户,same country
但它没有显示same state
。
模型.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True)
country = models.CharField(max_length=30,null=True,blank=True)
state = models.CharField(max_length=30,null=True,blank=True)
视图.py
def show_user(request.user):
show = Profile.objects.filter(country=request.user.profile)
show_state = Profile.objects.filter(state=request.user.profile)
context = {'show':show,'show_state':show_state}
return render(request, 'show_user.html', context)
当我尝试在模板中访问{{ show }}时,它显示两个用户已将他们的国家/地区设置为相同,request.user
但是当我尝试在模板中访问{{ show_state }}时,它什么也没显示。
我不知道,我在访问时做错了什么。任何帮助,将不胜感激。先感谢您。
注意:- 我正在使用外部库在 html 中显示国家和州的选择。
解决方案
好像有filter
问题。
request.user.profile # Profile Object
# you're filtering by matching country with request.user.profile
Profile.objects.filter(country=request.user.profile)
# Similar for state
Profile.objects.filter(state=request.user.profile)
你想要做的是filter
使用request.user.profile.state
and request.user.profile.country
。
# Since this is a view
# Method parameter should be request instead of request.user
def show_user(request):
show = Profile.objects.filter(country=request.user.profile.country)
show_state = Profile.objects.filter(state=request.user.profile.state)
context = {'show':show,'show_state':show_state}
return render(request, 'show_user.html', context)
虽然这应该可以解决您当前的问题。
建议
使用 Django,您实际上可以在同一查询中过滤具有与用户匹配的国家和状态的配置文件。
def show_user(request):
user_profile = request.user.profile
valid_profiles = Profile.objects.filter(country=user_profile.country, state=user_profile.state)
context = {'valid_profiles': valid_profiles}
return render(request, 'show_user.html', context)
推荐阅读
- monitoring - 如何从 Datadog RUM 中编辑地理位置数据?
- postgresql - 无法将 PostgreSQL(pgAdmin 4) 连接到 Google Cloud Platform
- r - R中多元正态分布的数值积分
- python - 如何捕获未佩戴面罩的人的图像并将图像存储在本地桌面?在 Python 中
- google-cloud-platform - 模式 PCollections 上的等值连接 - 不起作用
- python - 在一个程序运行期间将建立多少个 websockets 连接?
- sql - SQL 只删除特定列中的值?
- javascript - React 路由器 v5 仅在所有路由上呈现索引页面
- python - 如何在 macOS 终端中打开 IDLE 文件(filename.py)?
- r - 使用 R 从数据框中排除基于条件的某些行