0

In Django I have a function that provides a list of all URL Patterns for my system. I am attempting to create a search feature that shows users links to a list of urls that they have permissions to view, but I cannot seem to figure out how to grab the associated permission from the view function.

How can I do this?

Here is my code so far:

def get_url_patterns():
    from django.apps import apps


    list_of_all_urls = list()
    for name, app in apps.app_configs.items():
        mod_to_import = f'apps.{name}.urls'
        try:
            urls = getattr(importlib.import_module(mod_to_import), "urlpatterns")
            list_of_all_urls.extend(urls)
        except ImportError as ex:
            # is an app without urls
            pass

    for thing in list_of_all_urls:
        # print(type(thing))
        # print(type(thing.callback.__name__))
        print(thing.callback.__dict__)

    return list_of_all_urls

Cœur
  • 37,241
  • 25
  • 195
  • 267
ViaTech
  • 2,143
  • 1
  • 16
  • 51

1 Answers1

0

Hey there are many mays to do it

  1. Use already build decorator

    from django.contrib.auth.decorators import login_required,user_passes_test

    User it as @user_passes_test(lambda u: Model.objects.get(condition) in queryset)

  2. You can make your own decorator

from django.contrib.auth.decorators import login_required, user_passes_test user_login_required = user_passes_test(lambda user: user.is_active, login_url='/')

def active_user_required(view_func):
         decorated_view_func = login_required(user_login_required(view_func))
         return decorated_view_func
@active_user_required
def index(request):
    return render(request, 'index.html')

List item

Sanjay Kumar
  • 129
  • 7
  • I would down vote this normally: I'm not certain your answer relates to my question. I have permission decorators on all of my views, some built in and some custom built, this is how permissions are best implemented in views for Django in my experience. What I need is each view's associated permissions based on the grabbed URL patterns so I can check to see if the current request.user has permission to access the view. I have currently created a solution for this that hardcodes my permissions to search but I want a more automated solution as scaling that feature seems taxing – ViaTech Sep 28 '19 at 16:16