Limiting access to authenticated user

81 Views Asked by At

I'm trying to limit access to authenticated user on a photo gallery site. I want an authenticated user to see all photos, and unauthenticated one to see only three.

I am using a third-party library called Photologue which has a class GalleryDetailView() which inherits from DetailView(). I want to override the get_context_data() method on the gallery detail view, and add there the code that prepares a list of the photos to display, and adds that list to the template context. So far I have:

class CustomGalleryDetailView(GalleryDetailView):

    def get_context_data(self, **kwargs):
        context = super(CustomGalleryDetailView, self).get_context_data(**kwargs)
        if not self.request.user.is_authenticated():
            items = OrderedDict(itertools.islice(context.iteritems(), 4))
            return items

        else:
            return context

EDIT: Based on some answers, I now have:

class CustomGalleryDetailView(GalleryDetailView):

    def get_context_data(self, **kwargs):
        context = super(CustomGalleryDetailView, self).get_context_data(**kwargs)
        if not self.request.user.is_authenticated():
            context['object'] = Gallery.objects.filter()[:3]
            return context

        else:
            return context

But for some reason, both authenticated and unauthenticated users still see all photos. I know the authentication is working because I've been toying around with this for hours, and have seen different results (just not the ones I need).

2

There are 2 best solutions below

0
On

First of all, move out context = ... out of if. Secondly, add prints or breakpoints to verify that you are in first of second part of if.

0
On

Although I didn't figure out the problem with the mixin/view approach, I solved the issue with a simple if/else inside the template:

{% if user.is_authenticated %} {% for photo in gallery %} ... {% endfor %} {% else %} {% for photo in gallery|slice:":3" %} ... {% endfor %} {% endif %}

It seemed somehow more 'correct' to limit results in the view rather than handle the logic inside the template, but it's a simple solution and it works.