how to get current_app for using with reverse in multi-deployable reusable django application?

  • Last Update :
  • Techknowledgy :

As Will Hardy suggested you'll have to keep app_name the same for both instances (or not define it at all, it will default to the app the included urls reside in). Define a separate namespace for each app instance though:

urlpatterns = patterns('',
   (r '^carphotos/', include('webui.photos.urls', app_name = "webui_photos", namespace = 'car-photos')),
   (r '^userphotos/', include('webui.photos.urls', app_name = "webui_photos", namespace = 'profile-photos')),
)

To find the currently active app, django.urls.resolve can be used:

r = resolve(request.path)
r.app_name # the app name
r.namespace # the the currently active instance

So you'll have to update your views (this assumes using the class based views) accordingly:

from django.urls
import resolve
from django.views.generic
import TemplateView

class AlbumCreateView(TemplateView):
   template_name = 'path/to/my/template.html'

def render_to_response(self, context, ** response_kwargs):
   response_kwargs['current_app'] = resolve(self.request.path).namespace
return super(AlbumPageView, self).render_to_response(context, ** response_kwargs)

To reverse urls in views, the current app instance has to be passed in manually:

reverse('webui_photos:album-create', current_app = resolve(self.request.path).namespace))

In your urls, you have a different app_name even though it's the same app. Set the app_name to the same thing, and set namespace uniquely for each instance. eg.

urlpatterns = patterns('',
   (r '^carphotos/', include('webui.photos.urls', app_name = "webui_photos", namespace = 'car-photos')),
   (r '^userphotos/', include('webui.photos.urls', app_name = "webui_photos", namespace = 'profile-photos')), )

Suggestion : 2

I'm writing reusable app. And I want to deploy it several times.,As Will Hardy suggested you'll have to keep app_name the same for both instances (or not define it at all, it will default to the app the included urls reside in). Define a separate namespace for each app instance though:,Now the url tag will automatically reverse to the correct namespace and still allow reversing to a specific app namespace if needed:,But how to get this current_app? I thought the answer is something simple. But I can't find it in django documentation.

Here is urls.py:

urlpatterns = patterns('',
   (r '^carphotos/', include('webui.photos.urls', app_name = 'car-photos')),
   (r '^userphotos/', include('webui.photos.urls', app_name = 'profile-photos')), )

and photos/urls.py:

urlpatterns = patterns('webui.photos.views',
   url(r '^$', album_list, name = "album-list") url(r '^newalbum/$', album_page, {
      'create': True
   }, name = "album-create"), )

As Will Hardy suggested you'll have to keep app_name the same for both instances (or not define it at all, it will default to the app the included urls reside in). Define a separate namespace for each app instance though:

urlpatterns = patterns('',
   (r '^carphotos/', include('webui.photos.urls', app_name = "webui_photos", namespace = 'car-photos')),
   (r '^userphotos/', include('webui.photos.urls', app_name = "webui_photos", namespace = 'profile-photos')),
)

To find the currently active app, django.urls.resolve can be used:

r = resolve(request.path)
r.app_name # the app name
r.namespace # the the currently active instance

So you'll have to update your views (this assumes using the class based views) accordingly:

from django.urls
import resolve
from django.views.generic
import TemplateView

class AlbumCreateView(TemplateView):
   template_name = 'path/to/my/template.html'

def render_to_response(self, context, ** response_kwargs):
   response_kwargs['current_app'] = resolve(self.request.path).namespace
return super(AlbumPageView, self).render_to_response(context, ** response_kwargs)

To reverse urls in views, the current app instance has to be passed in manually:

reverse('webui_photos:album-create', current_app = resolve(self.request.path).namespace))

Suggestion : 3

Post the package on a public repository, such as the Python Package Index (PyPI). packaging.python.org has a good tutorial for doing this.,Reusability is the way of life in Python. The Python Package Index (PyPI) has a vast range of packages you can use in your own Python programs. Check out Django Packages for existing reusable apps you could incorporate in your project. Django itself is also a normal Python package. This means that you can take existing Python packages or Django apps and compose them into your own web project. You only need to write the parts that make your project unique.,A Python package provides a way of grouping related Python code for easy reuse. A package contains one or more files of Python code (also known as “modules”).,Modifying the user libraries can affect other Python software on your system.

mysite /
   manage.py
mysite /
   __init__.py
settings.py
urls.py
asgi.py
wsgi.py
polls /
   __init__.py
admin.py
apps.py
migrations /
   __init__.py
0001_ initial.py
models.py
static /
   polls /
   images /
   background.gif
style.css
templates /
   polls /
   detail.html
index.html
results.html
tests.py
urls.py
views.py
templates /
   admin /
   base_site.html
=== ==
Polls
   ===
   ==

   Polls is a Django app to conduct web - based polls.For each question,
   visitors can choose between a fixed number of answers.

Detailed documentation is in the "docs"
directory.

Quick start
-- -- -- -- -- -

1. Add "polls"
to your INSTALLED_APPS setting like this::

   INSTALLED_APPS = [
      ...
      'polls',
   ]

2. Include the polls URLconf in your project urls.py like this::

   path('polls/', include('polls.urls')),

   3. Run ``
python manage.py migrate``
to create the polls models.

4. Start the development server and visit http: //127.0.0.1:8000/admin/
   to create a poll(you 'll need the Admin app enabled).

      5. Visit http: //127.0.0.1:8000/polls/ to participate in the poll.
[build - system]
requires = ['setuptools>=40.8.0', 'wheel']
build - backend = 'setuptools.build_meta:__legacy__'
[metadata]
name = django - polls
version = 0.1
description = A Django app to conduct web - based polls.
long_description = file: README.rst
url = https: //www.example.com/
   author = Your Name
author_email = yourname @example.com
license = BSD - 3 - Clause # Example license
classifiers =
   Environment::Web Environment
Framework::Django
Framework::Django::X.Y # Replace "X.Y"
as appropriate
Intended Audience::Developers
License::OSI Approved::BSD License
Operating System::OS Independent
Programming Language::Python
Programming Language::Python::3
Programming Language::Python::3::Only
Programming Language::Python::3.8
Programming Language::Python::3.9
Topic::Internet::WWW / HTTP
Topic::Internet::WWW / HTTP::Dynamic Content

[options]
include_package_data = true
packages = find:
   python_requires = >= 3.8
install_requires =
   Django >= X.Y # Replace "X.Y"
as appropriate
from setuptools
import setup

setup()
include LICENSE
include README.rst
recursive - include polls / static *
   recursive - include polls / templates *

Suggestion : 4

How to get current_app for using with reverse in multi-deployable reusable Django application?,How to create an object for a Django model with a many to many field?,How to create a Django reverse url with a parameter,How to serialize three models with many to many relationships in Django Rest Framework

using serializer-method field can be an option for this case. Our goal is get product information from category serializer. So for this

class CategorySerializer(serializers.ModelSerializer):
   products = serializers.SerializerMethodField()

class Meta:
   model = Category
fields = ('') # add relative fields

def get_products(self, obj):
   products = obj.product_set.all() # will
return product query set associate with this category
response = ProductSerializer(products, many = True).data
return response

Suggestion : 5

Last modified: Apr 28, 2022, by MDN contributors

# Read SECRET_KEY from an environment variable
import os
SECRET_KEY = os.environ['SECRET_KEY']

# OR

# Read secret key from a file
with open('/etc/secret_key.txt') as f:
   SECRET_KEY = f.read().strip()
# SECURITY WARNING: keep the secret key used in production secret!
   # SECRET_KEY = "cg#p$g+j9tax!#a3cup@1$8obt2_+&k3q+pmu)5%asj6yjpkag"
import os
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'cg#p$g+j9tax!#a3cup@1$8obt2_+&k3q+pmu)5%asj6yjpkag')
# SECURITY WARNING: don 't run with debug turned on in production!
# DEBUG = True
DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False'
export DJANGO_DEBUG = False
python3 manage.py check--deploy
git clone https://github.com/<your_git_user_id>/django_local_library.git