got an unexpected keyword argument 'pk' when use decorator in django

Viewed 583

i want to run decorator function before my view's dispatch method

below is my decorators.py

from django.urls import reverse
from django.shortcuts import render
from django.shortcuts import redirect

def check_point(point=None):
  def decorator(view_func):
    def wrap(request, *args, **kwargs):
      price = point or request.get_object().price
      if request.user.point.get_point() >= price:
        return view_func(request, *args, **kwargs)
    return wrap
  return decorator

and my view code

@method_decorator(check_point, name='dispatch')
class CheckWinningView(SingleObjectMixin, RedirectView):
  model = Product

But when I run the code, I get the following error: enter image description here

I'm not sure why I'm getting this error.

I know that 'pk' must be entered unconditionally due to the characteristics of singleobjectmixin.

how can i fix it?

1 Answers

You need to call the check_point function when you decorate the function, so:

#            call check_point ↓
@method_decorator(check_point(), name='dispatch')
class CheckWinningView(SingleObjectMixin, RedirectView):
  model = Product

call_checkpoint() will then return the decorator function, and that will be applied as decorator on the method.

In order to decorate a class-based view, often a mixin is used instead of a decorator, for example the LoginRequiredMixin [Django-doc] to prevent people from seeing a page if they did not log in.

Related