How to serve "AnonymousUser" with user-based filtering

I have the following model

class Team(models.Model):
    name = models.CharField(max_length=100)
    members = models.ManyToManyField(User, related_name="members", blank=True, null=True)

And the next view (controller)

def my_teams(request):
    my_list = Team.objects.filter(members=request.user).order_by('name')
    return render_to_response('teams/index.html', {'my_list': my_list})

This works when the user is logged in, but when testing, I get the following error: anonymous user.

Exception Value: int() argument must be a string or a number, not 'AnonymousUser'

How to serve anonymous users? Is this being handled in my template or view?

Any advice on how to achieve this would be greatly appreciated.

+3
source share
1 answer

I think I can solve this by changing my mind as something:

def my_teams(request):
    if request.user.is_authenticated():
        my_list = Team.objects.filter(members=request.user).order_by('name')
        return render_to_response('teams/index.html', {'my_list': my_list})
    else:
        return render_to_response('teams/index.html', {})

Is it best practice to not return anything? How do I handle this in my template now?

+3
source

Source: https://habr.com/ru/post/1758715/


All Articles