Django:如何编写一个在重定向函数后接受输入的装饰器

Django : How write a decorator that takes an input after a redirect function

我想编写一个装饰器,它接受来自重定向函数的输入(值:id_contrat)。如果我再解释一下。用户在表单中选择一个值,然后将该值重定向到另一个视图“主页”。我想检查用户是否拥有这个值的权限!所以我需要把它放在我的装饰器里。如何将这个值添加到我的装饰器中。

I tried something but it is not working : `TypeError: wrapper_func() got an unexpected keyword argument 'id_contrat'`

我的看法:

@authenticated_user
def selectcontrat(request) :

    context = initialize_context(request)
    form_client = SelectClient(request.POST, user=request.user)
    if form_client.is_valid():
        id_contrat = request.POST.get("ID_Customer")
    
        return redirect(reverse('home', args=(id_contrat,)))

    context['form_client'] = form_client

    return render(request, 'base/selectcontrat.html', context)


@authenticated_user
@check_user_rights
def home(request, id_contrat=None):
    context = initialize_context(request)

    return render(request, 'home.html', context)

url 定义:

from django.urls import path
from . import views

urlpatterns = [
    path('home/<int:id_contrat>/', views.home, name="home"),
    path('', views.loginAD, name="login"),
    path('signin', views.sign_in, name='signin'),
    path('callback', views.callback, name='callback'),
    path('selectcontrat', views.selectcontrat, name='selectcontrat')

表格:

class SelectClient(forms.Form):

    ID_Customer = forms.ChoiceField(label="Company :")  
        
    
    def __init__(self, *args, **kwargs) :
        self.user = kwargs.pop('user')
        super(SelectClient, self).__init__(*args, **kwargs)

        id_client_list = AADJNTGroup.objects.filter(ID_User_id=self.user.id).values_list('ID_Group_id', flat=True)
        id_client_list = list(id_client_list)

        client_choices = Groups.objects.all().filter(ID__in=id_client_list).values_list('IDCustomer','GroupName')
        
        self.fields['ID_Customer'].choices = client_choices

          

已编辑:装饰者

def check_user_rights(id_contrat) :

def wrapper_func(view_func) :
    @wraps(view_func)
    def wrapper(request, *args, **kwargs) :
        print(kwargs["id_contrat"])
        return view_func(request, *args, **kwargs)
    return wrapper
return wrapper_func
        

您应该从装饰器中删除 id_contrat 参数,除非您计划在装饰视图时传递此参数,例如 @check_user_rights(my_id_contrat)

def check_user_rights():
    def wrapper_func(view_func):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            # This prints all the keyword arguments passed to your view
            # and should contain id_contrat from your url
            print(kwargs)
            return view_func(request, *args, **kwargs)
        return wrapper
    return wrapper_func

@check_user_rights()
def home(request, id_contrat=None):
    context = initialize_context(request)
    return render(request, 'home.html', context)

您也可能会在 Having trouble making a custom django view decorator (with args)

的答案的评论中找到一些价值