Search code examples
pythondjangodjango-generic-viewsdetailview

How to use Django's DetailView (or some built-in view class) for a home page?


I'm building an app in Django and I would like to set up a home page for authenticated users.

I thought it was best to use de built-in generic.DetailView for this, given that the details I want to show in the page are those of the identified user. The thing is, this class needs to receive the id of the target entity through the URL as a decimal pk argument. However, the information about the entity, is in request.user, and I would like to avoid repeating that information so as not to show my user ids in the urls.

I would imagine that getting the request within the get_object method would do the trick, but it does not take arguments.

Is this possible? Is this a good idea? Are there any alternatives that I may be missing?


Solution

  • The DetailView only needs the pk or slug to fetch the object. If you override get_object then it is not required. In the get_object method, you can access the user with self.request.user.

    Finally, if your view uses the logged in user, then you can use the LoginRequiredMixin to ensure that only logged in users can access the view.

    from django.contrib.auth.mixins import LoginRequiredMixin
    
    class MyDetailView(LoginRequiredMixin, DetailView):
        ...
        def get_object(self):
            return self.request.user