问题
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