how to handle common code in a django project which is used by multiple apps

  • Last Update :
  • Techknowledgy :

so my project structure looks similar to this:

mysite /
   manage.py
mysite /
   ...
   shared
   ...
   app1
   ...
   app2
   ...
   app3
   ...
   ...

Suggestion : 2

Since we moved the polls directory out of the project, it’s no longer working. We’ll now fix this by installing our new django-polls package.,Try building your package with python setup.py sdist (run from inside django-polls). This creates a directory called dist and builds your new package, django-polls-0.1.tar.gz.,Try building your package with python setup.py sdist (run from inside django-polls). This creates a directory called dist and builds your new package, django-polls-0.1.tar.gz. ,After the previous tutorials, our project should look like this:

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 : 3

We can add an app by using the startapp command so let's add the posts app now. Using the tree command we can then see our complete updated structure.,The first step, always, is to install Django within a dedicated virtual environment. Let's assume we're creating a code directory on our Desktop (I'm using a Mac). The commands would be as follows:,Django's definition of an "app" is often confusing to newcomers. In this post we'll examine the four major concepts of Django architecture by building out a basic blog web application.,Django apps may seem like overkill when you're starting out but they provide much needed structure and flexibility to any Django web application. Further the ability to separate one out completely, if desired, has led to a robust ecosystem of Django 3rd Party Packages that improve the overall community immensely.

$ cd~/Desktop
$ mkdir code && cd code
$ pipenv install django~ = 3.1 .0
$ pipenv shell
   (code) $
(code) $ django - admin startproject config.
   (code) $ tree
   .├──Pipfile├── Pipfile.lock├── config│├── __init__.py│├── settings.py│├── urls.py│└── wsgi.py└── manage.py
# config / settings.py
INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
]
(code) $ python manage.py startapp posts(code) tree
   .├──Pipfile├── Pipfile.lock├── config│├── __init__.py│├── settings.py│├── urls.py│└── wsgi.py├── manage.py└── posts├── __init__.py├── admin.py├── apps.py├── migrations│└── __init__.py├── models.py├── tests.py└── views.py
# config / settings.py
INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'posts', # new
]

Suggestion : 4

Break logic into small methods on your models. This allows you use it multiple times from multiple sources (admin interface UI, front-end UI, API endpoints, multiple views) in a few lines of code instead of copy-pasting tons of code. So next time you’re sending a user an email, extend the model with an email function instead of writing this logic in your controller.,Django provides a very nice feature called Management Commands. Just use it instead of reinventing wheels and writing raw Python scripts for your project utilities.,You can read more about the problem in the Django Best Practices project. The solution is simple: Write fat models and skinny views, so let’s do it in your next project (or refactor your current one).,This also makes your code easier to unit test because you can test the email logic in one place, rather than repeatedly in every controller where this takes place.

Check out the minimal configuration example:

from split_settings.tools
import optional, include

include(
      'components/base.py',
      'components/database.py',
      'components/*.py',

      # the project different envs settings optional('envs/devel/*.py'),
      optional('envs/production/*.py'),
      optional('envs/staging/*.py'),

      #
      for any local settings optional(‘local_settings.py '),)

Here is example structure for a portal application which has a lot of resources and Python modules.

root @c5b96c395cfb: /test# tree project/apps / portal /
   project / apps / portal / ├──__init__.py├── admin.py├── apps.py├── management│├── __init__.py│└── commands│├── __init__.py│└── update_portal_feeds.py├── migrations│└── __init__.py├── models.py├── static│└── portal│├── css│├── img│└── js├── templates│└── portal│└── index.html├── templatetags│├── __init__.py│└── portal.py├── tests.py├── urls.py└── views.py

11 directories, 14 files

You’ll end up with a project structure like this:

root @c5b96c395cfb: /test# tree -L 3
   .├──deploy│├── chef│└── docker│├── devel│└── production├── docs├── logs├── manage.py├── media├── project│├── __init__.py│├── apps││├── auth││├── blog││├── faq││├── pages││├── portal││└── users│├── conf│├── settings.py│├── static│├── templates│├── urls.py│└── wsgi.py└── static└── admin├── css├── fonts├── img└── js

25 directories, 5 files

Suggestion : 5

Within the templates directory create a new file called home.html. You can do this within your text editor: in Visual Studio Code go to the top left of your screen, click on “File” and then “New File.” Make sure to name and save the file in the correct location.,This means we would need to create a new templates directory, a new directory with the name of the app, pages, and finally our template itself which is home.html.,Well we can! Let’s create a base.html file containing a header with links to our two pages. We could name this file anything but using base.html is a common convention. In your text editor make this new file called templates/base.html.,Use git status to see all our code changes. Notice that the .venv directory with our virtual environment is included? We don’t want that. In your text editor create a new hidden file, .gitignore, so we can specify what Git will not track.

# Windows
   >
   cd onedrive\ desktop\ code >
   mkdir pages >
   cd pages >
   python - m venv.venv >
   .venv\ Scripts\ Activate.ps1(.venv) > python - m pip install django~ = 4.0 .0(.venv) > django - admin startproject django_project.
   (.venv) > python manage.py startapp pages

# macOS
   %
   cd~/desktop/code %
   mkdir pages %
   cd pages %
   python3 - m venv.venv %
   source.venv / bin / activate(.venv) % python3 - m pip install django~ = 4.0 .0(.venv) % django - admin startproject django_project.
   (.venv) % python3 manage.py startapp pages
# django_project / settings.py
INSTALLED_APPS = [
   "django.contrib.admin",
   "django.contrib.auth",
   "django.contrib.contenttypes",
   "django.contrib.sessions",
   "django.contrib.messages",
   "django.contrib.staticfiles",
   "pages.apps.PagesConfig", # new
]
(.venv) > python manage.py migrate(.venv) > python manage.py runserver
└──
pages├── templates├── pages├── home.html
(.venv) > mkdir templates
# django_project / settings.py
TEMPLATES = [{
   ...
   "DIRS": [BASE_DIR / "templates"],
   # new
   ...
}, ]