views:

47

answers:

1

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 following 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 fantastic when a user is logged in, but I receive the following error while testing as an Anonymous user.

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

How do I cater for Anonymous users? Is this handled in my template or view?

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

+1  A: 

I think I can solve this by modifying my view to be something like:

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 this best practice to return nothing? How would I now handle this in my template?

Jamie Woods
You could perhaps use [`@login_required`](http://docs.djangoproject.com/en/dev/topics/auth/#the-login-required-decorator) decorator to forbid access to anonymous users. If you only want to return something else for anon your on the right track.
rebus
thanks rebus - that might come in handy later on. For this particular view, i'm happy for anonymous views (I've left a little code out of this to make it easier to ask my question without making it confusing).Okay, so, to cater for the situation where is_autenticated() = false and thus returns nothing, i've added a condition to my template: `{% if user.is_active %}`.This should show the returned content when a user is authenticated, otherwise it's hidden and users only see anonymous content on the page. I hope this makes sense.
Jamie Woods
Careful, [`user.is_active`](http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.is_active) is not the same as [`user.is_authenticated()`](http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.is_authenticated). Also, for example, instead of additional checks in template you could serve some other template for anon.
rebus
thanks again rebus, I've reconsidered using `user.is_active` and gone with `user.is_authenticated()`.Having some other issue with my template now... for some reason this page, and this page only keeps returning that i'm not authenticated, when I know I am. all other pages are fine. next hurdle :)
Jamie Woods
Well, i've learnt heaps tonight - by default templates render with a Context instance, however generic views render with a RequestContext instance. I rendered the template with a RequestContext instance, and surly enough the template is aware of the session now.
Jamie Woods