简体   繁体   中英

How to access parameters value form url in django decorators

I want to make a decorators which prevents the user to see others profile but can see own profile. If the user has id passed in url as http://example.com/user/?id=5 i want to get the value id=5 in my django decorator. How can I get it any example ?

def admin_or_ownership_required(owner):
    def check_admin_or_owner(user):
        # pk = request.GET.get('pk', None)
        # if pk is not None and pk == user.id:
        #     return True
        if owner == 'Account':
            if user.is_superuser or (user.is_active and (user.role == 'admin' or user.role == 'owner')):
                return True
            else:
                return False
        elif owner == 'User':
            if user.is_superuser or (user.is_active and (user.role == 'admin' or user.role == 'owner')):
                return True
            else:
                return False
        else:
            return False
    return user_passes_test(check_admin_or_owner)

this is my view code

class AccountDetailView(DetailView):
    template_name = 'api/account_detail.html'
    model = Account

    @method_decorator(admin_or_ownership_required('Account'))
    def dispatch(self, *args, **kwargs):
        return super(AccountDetailView, self).dispatch(*args, **kwargs)

How can I use the request argument in admin_or_ownershipl_required decorator

def check_login(method):
   @functools.wraps(method)
   def wrapper(request, *args, **kwargs):
       if request.GET['id'] == request.user.id
           # Give your redirect url
      return method(request, *args, **kwargs)
   return wrapper

You could use a mixin for your View, where you limit your case queryset, something like:

class MixinRestrictedAccount(object):
    def get_queryset(self):
        return Account.objects.filter(id=self.request.user.id)


class AccountDetailView(MixinRestrictedBox, DetailView):
    [..]

Try to dump the value of kwargs, from there you can access the url parameters. for example : if you have Url like :

/users/(?P<username>\w+)/$

you can access that value by kwargs parameter , that is passed in your decorator method. You can access that by:

kwargs.get("username")

If you want to access url parameters by GET method, then you can try like this :

request.GET.get("username")

for URL's like :

/users/?username=dominic

Thanks .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM