Search code examples
pythondjangodjango-viewsdjango-urlsdjango-class-based-views

Get url kwargs in class based views


I need to retrieve the value of the pk written in the url in my class based view:

path('<int:pk>/data/', views.DataView.as_view(), name='data'),

However, what I saw everywhere was the pk retrieved in the definition of methods like get or post.

What I want is to be able to use it to define my class variables, because I need to do get the same value from this pk in every method inside my class, like below:

class DataView(ContextMixin, UpdateView):
    pk = get_pk_from_url
    ...
    value = ...

    def get(self, request, *args, **kwargs):
        value = self.value
        # Do something with value

    def post(self, request, *args, **kwargs):
        value = self.value
        # Do something with value

I got an idea while writing this question, which is to define a method that will do what I need, then calling this method in my other methods.

class DataView(ContextMixin, UpdateView):

    def get_value(self):
        self.pk = self.kwargs['script_id']
        ...
        self.value = ...

    def get(self, request, *args, **kwargs):  
        self.get_value()
        value = self.value
        # Do something with value

    def post(self, request, *args, **kwargs):
        self.get_value()
        value = self.value
        # Do something with value

However, I don't know if there's another way, which is why I still wanna ask my question.


Solution

  • Thanks to @WillemVanOnsem's comment, I was able to use the setup method (doc here) in order to define everything I needed to define. So in the end I get something like that :

    class DataView(View):
    
        def setup(self, request, *args, **kwargs):
            self.pk = kwargs['pk']
            ...
            self.value = ...
            return super().setup(request, *args, **kwargs)
    
    
        def get(self, request, *args, **kwargs):
            value = self.value
            
    
        def post(self, request, *args, **kwargs):
            value = self.value
    

    The setup method being called before the get and post ones, the class attributes declared in it can then be used in the other methods.