[Answered ]-How to route DetailView to inherit user and slug

2👍

To include the username in the detail view, you first need to add it to your url patterns.

url(r'^(?P<username>[-\w]+)/(?P<slug>[-\w]+)/$', TrackDetails.as_view(), name='track-details'),

Then, since you are using DetailView, you need to override get_object so that you use the username and slug to fetch the object.

from django.shortcuts imporg get_object_or_404

class TrackDetails(DetailView):
    model = Track

    def get_object(self, queryset=None):
        return get_object_or_404(
            Track, 
            user__username=self.kwargs['username'],
            slug=self.kwargs['slug'],,
        )

Displaying the display_name of the user in the template is a separate problem. If you have a user, you can follow the one to one key backwards to the profile with user.userprofile. Therefore, in your template you can show the display_name with.

{{ object.user.userprofile.display_name }}

0👍

To access username and slug first pass in the two keywords:

url(r'^/(?P<username>\d+)/(?P<slug>[-\w]+)/$', get_userpage, name='track-details'),

Then check if Track.objects.filter(slug=slug, username=username) returns anything:

def get_userpage(request, username, slug):
   """Render user page"""
   user = User.objects.get(username=username)
   track_song = Track.objects.filter(slug=trackslug, user=user).first() 
   if track_song:
       # return song page for user

   else:
      # try to return user
      track_user = Track.objects.filter(user=user).first() 
      if track_user:
          # return user page

   # if nothing returned above 
   # return 404

Previous suggestions:

  • you can you use get_object_or_404(Track, slug=slug) in your view to return the correct response.

  • you could also redirect a user to their unique combination of username and slug using:

    redirect(‘track-username-slug’, username=myusername slug=myslug, permanent=True)

where track-username-slug is your named url

👤djq

Leave a comment