Skip to content
Advertisement

Showing all the users who have set their country same as request.user

I am building a BlogApp and I am trying to show all the users which set their Countries similar to request.user.

For Example : If user_1 is request.user and selected state choice Victoria and country Australia and then user_2 registered and set the same state Victoria and country Australia.

So i want to show all the users that have set their Country and state same to request.user BUT When i access these types of users then It is just showing all users of same country BUT it is not showing of same state.

models.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)

views.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)

When i try to access {{ show }} in template then it shows two user have set their country same to request.user BUT When i try to access {{ show_state }} in template it shows nothing.

I have no idea, what am i doing wrong in accessing. Any help would be Appreciated. Thank You in Advance.

Note :- I am using external library to show country and state choices in html.

Advertisement

Answer

There seems to be a filter problem.

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)

What you want to do is filter using 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)

While this should solve your current problem.

Suggestion

With Django, you can actually filter Profiles with country and state that matches user’s in the same query.

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)

Advertisement