首页 > 解决方案 > 如果用户选择美国,如何显示美国用户的所有帖子(在 CharField Choices 中)

问题描述

我正在构建一个 BlogApp,但我遇到了一个问题。request.user如果在中选择美国,我想显示所有美国邮政CharField

有一个名为“位置”的属性,它有两个选择“美国”和“澳大利亚”。我希望它只显示“用户选择美国时的美国帖子”。

当用户选择“美国”时,我想显示仅选择美国的用户的所有帖子。

如果用户选择“澳大利亚”,那么它会找到所有选择“澳大利亚”的用户并显示澳大利亚用户的帖子。

视图.py

def showing_post(request,user_id):
    profiles = get_object_or_404(Profile,user_id=user_id)
    you = request.user

    shows = 'none'
    show = 'none'
    if profiles.location == 'America':
        show = Profile.objects.order_by('location')

    elif profiles.location == 'Australia':
        shows = Profile.objects.order_by('location')

    context = {'shows':shows,'show':show,'profiles':profiles}
    return render(request, 'opens.html', context)

打开.html

    {% if profiles.location == '-------' %}

        {% for p in show %}

        {{ p.location }}

        {% endfor %}

    {% endif %}

问题

当我签入页面时,它会显示所有选择美国和澳大利亚位置的用户,所有用户都在显示。

我想做什么

我想要if request.user select America then show only users that have selected America , AND don't show the users of Australia

我试过什么

我也尝试过location__icontains,但没有奏效。

我不知道我做错了什么

任何帮助,将不胜感激

先感谢您

标签: pythonhtmldjangodjango-modelsdjango-views

解决方案


我也是 django 的新手,但你可以试试这个。

视图.py:

def showing_post(request,user_id):
    profile = get_object_or_404(Profile,user_id=user_id)
    profile_location = Profile.objects.filter(location=profile.location)
    context = {'show':profile_location,'profile':profile}
    return render(request, 'opens.html', context)

打开.html:

 user:{{ profile.user }}
    location:{{ profile.location }}
      <h4>Users in {{ profile.location }}:</h4>
    {% for p in show %}
     
    {{ p.user }}

    {{ p.location }}

    {% empty %}
 <h4>No other users found in {{ profile.location }}</h3>
 {% endfor %}

推荐阅读