Django - Generic View Subclassed - url Parameters
Asked Answered
E

2

4

I need to display a detail page for a video with some other data. For that I use DetailView that I have overridden to add some variables to the context.

Here are the code parts:

#urlconf
#...
  (r'viewtube/(?P<pk>\d+)$', VideoFileDetailView.as_view()),
#...

#view
class VideoFileDetailView(DetailView):
  model = VideoFile
  def get_context_data(self, **kwargs):
    context = super(VideoFileDetailView, self).get_context_data(**kwargs)
#    context['rates'] = VideoRate.objects.filter(video=11, user=1)
    return context

Here pk is the id of a video, I need to get the rates of the selected video by the current user.

Eldridgeeldritch answered 21/6, 2011 at 14:31 Comment(0)
G
4

It would have been useful to show the models. But I think you need to override get(), not get_context_data, as unfortunately the latter doesn't get passed the request, which you need in order to get the user. So:

def get(self, request, **kwargs):
    self.object = self.get_object()
    context = self.get_context_data(object=self.object)
    context['rates'] = VideoRate.objects.filter(video=self.object, user=request.user)
    return self.render_to_response(context)
Gooden answered 21/6, 2011 at 15:18 Comment(1)
Aparently from get_context_data() we can get the request trought self.request, thanks it's working with thatEldridgeeldritch
S
4

The request should be accessible at self.request. self.request is set at the beginning of the request (in View.dispatch) and should be available any of the subclass methods.

class VideoFileDetailView(DetailView):
  model = VideoFile
  def get_context_data(self, **kwargs):
    context = super(VideoFileDetailView, self).get_context_data(**kwargs)
    context['rates'] = VideoRate.objects.filter(video=11, self.request.user)
    # note that the object is available via self.object or kwargs.get("object")
    return context
Safar answered 21/6, 2011 at 16:47 Comment(3)
I also needed to filter on the VideoFile itself, so with video=self.object I'm getting what I'm searching for.Eldridgeeldritch
Thanks Yuji. I haven't experimented much with class-based views, and was a bit surprised that request wasn't explicitly passed to get_context_data.Gooden
Hmm you're right! It's a little more magical than I'm used to when going through code. Well, it's brand new ;)Tenorrhaphy

© 2022 - 2024 — McMap. All rights reserved.