In Django, How to get the currently running app from within a model on another app? -
basically trying use .get_absolute_url() return dynamic links in relative current app running, in other words reverse model url different url based on app being called.
let me try explain trying example, have 3 apps
- blog (serves shared data layer, contains models post, authors ... etc)
- bloggerway (serves view layer number one, uses blog app models display content in given layout)
- tumblrway (serves view layer, again uses blog app models display content in given layout)
my urls.py files goes like
---------- *project.urls.py* ---------- urlpatterns= [ url('/blogger/', include(bloggerway.urls.py, namespace='blogger'), url('/tumblr/', include(tumblrway.urls.py, namespace='tumblr'),] ---------- *bloggerway.urls.py* ---------- urlpatterns= [ url('/post/(?p<id>\d+)', blog.as_view(), name='blog'),] ---------- *tumblrway.urls.py* ---------- urlpatterns= [ url('/post/(?p<id>\d+)', blog.as_view(), name='blog'),]
my question is how can define .get_absolute_url() method post model knows app in , return correct url it.
example: if in bloggerway return '/blogger/post' if in tumblrway return '/tumblr/post'
i know can use reverse() function url given named pattern , accepts current_app= argument problem how can running app can pass it.
class post(...): def get_absolute_url(self): whoami = ... #get current app here, how! return reverse('post', current_app=whoami)
solutions want avoid:
- i can inherit post class in both of apps, override .get_absolute_url() there, hardcoding name space of each app in it. use class in app instead of directly using 1 defined model/table.(while offcourse avoid performing migrations class, better define somewhere else models.py)
implement property get_url() class. reverse function should includes "namespace:name" e.g
class post(...):... def get_blogger_url(self): return reverse("blogger:post", kwargs={"id":self.id}) # blogger def get_tumblr_url(self): return reverse("tumblr:post", kwargs={"id":self.id}) # tumblr
Comments
Post a Comment