get app name from url in django

一曲冷凌霜 提交于 2021-01-28 07:53:40

问题


I know how to get the url name with url resolve in django.

I want to treat all requests that come from a certain app similarly so I think I would do this by getting the app name from the url.

How can I do this?


回答1:


path you would be a headache as you would have to apply a lot of splits. A better way to do this is:

request.resolver_match which contains :

{'app_name': '', '_func_path': 'app_name.views.ClassName', 'args': (), 'func': , 'url_name': 'url-for-class', 'namespace': '', 'kwargs': {}, 'view_name': 'name-for-class', 'app_names': [], 'namespaces': []}

Using request.resolver_match._func_path will fetch you app_name along with ClassName




回答2:


Views aren't really tied to an app in the same way models are. They're really just python functions or classes (depending on FBV/CBV). You could resolve the view and parse the module name to "guess" what app its from.

A better solution, if you're using class based views, is to create a common base view for all views in a given app that implements the functionality.

Here's the boilerplate:

class SpecificAppView(View):
    def dispatch(self, request, *args, **kwargs):
        # Do something specific
        super(SpecificAppView, self).dispatch(request, *args, **kwargs)


class FirstView(SpecificAppView):
    pass


class AnotherView(SpecificAppView):
    pass



回答3:


I ended up getting this by extracting the info out of the request.path



来源:https://stackoverflow.com/questions/19261269/get-app-name-from-url-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!