If you are in the view and want to retrieve the app name using Python ( the app name will be used for further logic ), how would you do it ?
23
votes
7 Answers
28
votes
You could do:
from django.core.urlresolvers import resolve
....
resolve(request.path).app_name
See How to get current application in Django and resolve()
EDIT: You can now use request.resolver_match.app_name which avoids resolving a second time and avoids an import. Do it this way:
request.resolver_match.app_name
6
votes
6
votes
You can get application name from model: Book._meta.app_label.
I've found in django/contrib/admin/widgets.py:
class RelatedFieldWidgetWrapper(forms.Widget):
...
def get_context(self, name, value, attrs):
from django.contrib.admin.views.main import IS_POPUP_VAR, TO_FIELD_VAR
rel_opts = self.rel.model._meta
info = (rel_opts.app_label, rel_opts.model_name)
...
...
5
votes
3
votes
maybe this can help you..
from django.core import urlresolvers
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(self.__class__)
url = urlresolvers.reverse("admin:%s_%s_change" % (content_type.app_label,
content_type.model), args=(self.id,))
url will return you all adress and you can parse it for your app and model...
3
votes
so to sum up, If you're looking for the app_name of where your code is written, then use this:
app_name = __package__
However, if you need the app_name of where the object is being called (which might be in an app other than coding app), then use this:
import sys
from django.urls import resolve
app_name = sys.modules[resolve(request.path_info).func.__module__].__package__