首页 > 解决方案 > 显示所有将其国家设置为与 request.user 相同的用户

问题描述

我正在构建一个 BlogApp,我试图向所有将其设置Countriesrequest.user.

例如:如果user_1request.user和选中的州选择Victoria和国家Australia然后user_2注册并设置相同的州Victoria和国家Australia

所以我想显示所有将其设置为相同的用户,Country但是staterequest.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 中显示国家和州的选择。

标签: pythondjangodjango-views

解决方案


好像有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.stateand 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)

推荐阅读