Search code examples
djangolistviewuser-agent

How to use django-user-agents with class ListViews


I am building a blog and I have different templates for mobile and desktop versions, I have successfully implemented the user_agent identification for addressing mobile or desktop template for all of my functions as follow:

def about(request):
    user_agent = get_user_agent(request)

    if user_agent.is_mobile:
        return render(request, 'about-mobile.html')
    
    elif user_agent.is_pc:
        return render(request, 'about.html')

However, once I have to implement it to the ListView classes I really have no idea how to do that!

class homepage(ListView):
    model = DeathAd
    template_name = 'homepage.html'
    ordering = ['-id']
    paginate_by = 5

Solution

  • You can override the .get_template_names() method [Django-doc]. This method returns a list of templates that are then tried in the order of the list:

    class homepage(ListView):
        model = DeathAd
        template_name = 'homepage.html'
        ordering = ['-id']
        paginate_by = 5
    
        def get_template_names(self, *args, **kwargs):
            user_agent = get_user_agent(self.request)
            if user_agent.is_mobile:
                return ['about-mobile.html']
            elif user_agent.is_pc:
                return ['about.html']
            return super().get_template_names(*args, **kwargs)