What's the best practice when extending an application's template? - python

I've recently started studying Django(ver 1.9), and have a question about templates inheritance.
Suppose I have a Django project named mysite and an app named myapp.
And I created base template named base.html and another one named child.html, which inherits base.html.
So directory structure is like this:
(project root)
├── mysite
│   ├── settings.py
│   ├── urls.py
│   └── ...
├── myapp
│   ├── models.py
│   ├── views.py
│   ├── ...
│   └── templates
│   └── myapp
│   ├── base.html
│   └── child.html
└── manage.py
In this situation, I can inherit base.html like this.
<!-- on top of `child.html` -->
{% extends "myapp/base.html" %}
What I'm wondering is, I'm hard-coding the application name.
Are there any other ways of writing that avoid hard-coding the app name?
Or, it's OK and I don't need to worry about?
I came up with some workarounds.
1) Place base.html directly under templates directory
├── myapp
│   ├── models.py
│   ├── views.py
│   ├── ...
│   └── templates
│   ├── base.html # Here!
│   └── myapp
│   └── child.html
--> I think it causes file name crashing between applications.
2) Place base.html under project templates directory
-->In this case I don't want to share base.html between applications.
(base.html here is only for myapp, not other applications)

Both your base template and your child template are specific to your app, so both should live in the same myapp/ subdirectory. It's entirely acceptable to hard-code the dependency on myapp/base.html.

How about
|── myapp
│ ├── models.py
│ ├── views.py
│ ├── ...
│ └── templates
│ ├── base.html # Here!
│ └── child.html
│
then use
<!-- on top of `child.html` -->
{% extends "base.html" %}
Then dynamically changing your Template directory at the beginning of each views.py file.
from django.conf import settings
settings.TEMPLATE_DIRS =(os.path.join(settings.BASE_DIR,'myapp/templates').replace('\\','/'),)
You will have to do the same for every one of your apps.

Related

Setting up site-specific static folders with Django Sites

I am using Django Sites. I want to be able to have site-specific templates and static files.
My current directory structure is:
├── site_a
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
├── site_b
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
└── templates
├── site_a
│ ├── _navbar.html
│ ├── home.html
│ └── signup.html
└── site_b
├── _navbar.html
├── home.html
└── signup.html
I know that I can move templates inside the site_x directory if I declare it as an app in INSTALLED_APPS. Is there another way to tell Django to use templates in site_a/templates without declaring site_a as an app?
Also, I would also like to have site specific static files that are not placed in the project STATIC_ROOT so that my tree actually looks like:
.
├── site_a
│   ├── __init__.py
│   ├── settings.py
│   ├── static
│   │   ├── css
│   │   └── js
│   ├── templates
│   │   ├── _navbar.html
│   │   └── home.html
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
└── site_b
├── __init__.py
├── settings.py
├── static
│   ├── css
│   └── js
├── templates
│   ├── _navbar.html
│   └── home.html
├── urls.py
├── views.py
└── wsgi.py
You can setting static files via STATICFILES_DIRS (Django Docs) without declaring site_a:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
('site_a', os.path.join(BASE_DIR, 'site_a/static')),
'Full path to your file or directory'
)
And in template:
<script src="{% static 'site_a/js/my_site_a.js' %}" type="text/javascript"></script>
And with declaring of your app:
Store your static files(Django Docs) in a folder called static in your app: site_a/static/site_a/example.jpg.
And for templates same: site_a/templates/site_a/example.html
in your settings.py set APP_DIRS:
TEMPLATES = [
{
...,
'APP_DIRS': True,
...
},
]
See Support for template engines and Overriding templates:
APP_DIRS tells whether the engine should look for templates inside installed applications. Each backend defines a conventional name for
the subdirectory inside applications where its templates should be
stored.

Openshift Find Static Files From Django App

I am trying to add a css file to my django application which I am deploying on openshift. Currently, I am able to have the css file work when running locally with debug and all that. However, when I deploy my application to openshift, the css file does not have any effect. Many of the other questions online seem to be referring to old versions of django and openshift (lots of references to a wsgi folder that doesn't seem to be standard anymore and triggering collectstatic manually)
My understanding with the current django/openshift relationship is that I do not need to do collecstatic manually as I am using the django-ex template from openshift, and during the build process the collectstatic command is run automatically, the ouput of which I can see in the logs. Notably, I can see that my style.css file for my application gets copied into STATIC_ROOT in that log.
My project structure from my project root is thus:
.
├── db.sqlite3
├── djangoWrapper
│   ├── __init__.py
│   ├── settings.py
│   ├── templates
│   │   └── djangoWrapper
│   │   └── index.html
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
├── gitlab-ci.yml
├── ldap
│   ├── admin.py
│   ├── apps.py
│   ├── forms.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── static
│   │   └── ldap
│   │   └── style.css
│   ├── templates
│   │   └── ldap
│   │   ├── apiOffline.html
│   │   ├── index.html
│   │   ├── results.html
│   │   └── search.html
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── manage.py
├── openshift
├── README.md
├── requirements.txt
Here's what I am doing in my settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "ldap", "static"),]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
In my html files, I am then trying to load the css file with
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'ldap/style.css' %}">
in the <head> section.
I have attempted to do some debugging here because it would be assumed that the problem before I got to deployment was that my static files were not being put in the correct place/djgano couldn't find them. So I put some prints into my app and deployed it on openshift and got back the following info:
BASE_DIR: /opt/app-root/src
STATIC_ROOT: /opt/app-root/src/static
STATIC_URL: /static/
APP_VIEW_DIR: /opt/app-root/src/ldap/views.py
as well putting <p>"{%static 'ldap/style.css' %}"</p> into an html file, which displays as /static/ldap/style.css
From these tidbits, I know that the root directory for openshift is /opt/app-root/src/, that my static files are in /opt/app-root/src/static, and that my html is looking for the css file in /static/ldap/style.css. This seems like it should be working then as all of those directories line up. Is there something else about serving static files with django/openshift that I am missing here?
Finally got it working! I did use whitenoise, following the steps here.

why url cannot be generated after use blueprint

My current project looks like this:
├── __init__.py
├── pages
├── settings.py
├── static
├── templates
│   ├── article.html
│   ├── base.html
│   ├── index.html
│   └── posts.html
├── view
│   ├── article.py
│   ├── home.py
│   ├── index.py
│   └── postwall.py
I breaked views.py(no longer in the project) into files and those files cannot generate url dynamically anymore. What i had in article.py is:
from flask import Blueprint, render_template
from app import articles
article = Blueprint('article',__name__)
#article.route('/article/<path:path>/')
def page(path):
article = articles.get_or_404(path)
return render_template('article.html',page=article)
Meanwhile, posts.html which offers the link button to articles doesn't work anymore:
More ->
What is the problem?Did I miss something in the blueprint file?
solved. change
More ->
to
More ->
forgot to add blueprint name

Django: reusable templates: extend from base.html

What is the most reusable way for the "extends" method in django templates?
I have seen this very often:
{% extends 'base.html' %}
Unfortunately this does not work for me. The ordering of the template loader loads a template from a different app first.
I have a default django project and application created from scratch with Django1.8.
What should I do:
use a different name like 'my_base.html'
alter the ordering of the template loader
other solution?
The easy way to solve this problem is to namespace your templates. Create an application and inside the application directory (where you have the default views.py) create a templates directory, and inside that directory create a subdirectory which is the name of the application.
Imagine you have a project myproj and an app called registration, then you would have:
.
├── manage.py
├── myproj
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── registration
├── admin.py
├── __init__.py
├── migrations
│   └── __init__.py
├── models.py
├── templates
│   └── registration
│   └── base.html
├── tests.py
└── views.py
Now even if you have another application with a template called base.html, you can always load the specific template you need with {% extends 'registration/base.html' %}

Common folder/file structure in Flask app [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 months ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have just created a flask application and so far I have a router for my "Hello world!" template.
I would like to add a little (a lot) more functionality, but I wonder how I should structure the app directory.
What's the most common way of structuring a Flask app?
For instance, should I create a routes.py for all my routes?
Where does the SQLAlchemy stuff go?
Should models be in models.py?
You should check out the Larger Applications page in the Patterns section of the Flask docs: http://flask.pocoo.org/docs/patterns/packages/. It seems to be the model that most people follow when their application calls for a package instead of a module.
I believe views.py is what you are calling routes.py. After that, models would go in models.py, forms would go in forms.py, etc.
An example of a FlaskApp directory:
/yourapp
/run.py
/config.py
/app
/__init__.py
/views.py
/models.py
/static/
/main.css
/templates/
/base.html
/requirements.txt
/yourappenv
run.py - contains the actual python code that will import the app and start the development server.
config.py - stores configurations for your app.
__init__.py - initializes your application creating a Flask app instance.
views.py - this is where routes are defined.
models.py - this is where you define models for your application.
static - contains static files i.e. CSS, Javascript, images
templates - this is where you store your html templates i.e. index.html, layout.html
requirements.txt - this is where you store your package dependancies, you can use pip
yourappenv - your virtual environment for development
I would say if you split the application use divisional rather than functional structure.
I advocate this because you are more likely to work on 1 of these divisional components at any one time.
This type of structure lends itself well on marketplace or SaaS apps where different user groups use a different type of views. API only flask app I might use functional splitting.
Here are examples from Flask Blueprints. Blueprints are essentially documented advice how to split Flask application for more manageable pieces. More on this at : http://exploreflask.com/en/latest/blueprints.html
Here is an example of divisional splitting. See how each feature is grouped together.
yourapp/
__init__.py
admin/
__init__.py
views.py
static/
templates/
home/
__init__.py
views.py
static/
templates/
control_panel/
__init__.py
views.py
static/
templates/
models.py
Here is the functional example >
yourapp/
__init__.py
static/
templates/
home/
control_panel/
admin/
views/
__init__.py
home.py
control_panel.py
admin.py
models.py
I think flask is micro framework and now you must decide how create files and folders.
i use this way :
flask folders and files structure -> https://gist.github.com/4545740
this is near Django structure
i suggest you see some project to give you what you want
danjac / newsmeme — Bitbucket -> https://bitbucket.org/danjac/newsmeme/overview
sean-/flask-skeleton · GitHub -> https://github.com/sean-/flask-skeleton
Anyone looking for a simple beginner-friendly structure for the flask project may find this helpful:
|__movies
|__run.py
|__app
├── templates
│ └── index.html
│ └── signup.html
└── __init__.py
└── routes.py
Here 'movies' is the name given for the main application. It contains 'run.py' and a folder called 'app'.
'app' folder contains all necessary flask files such as 'templates' folder, '__init __.py', and 'routes.py'.
Contents of:
run.py:
from app import app
__init.py__:
from flask import Flask
app = Flask(__name__)
from app import routes
app.run(debug=True)
routes.py:
from app import app
#app.route('/')
#app.route('/index')
def index():
return "Hello, World!"
Beauty of flask lies in its flexibility. You can build django like project-structure easily. Django popularized abstraction of features in apps and making them reusable but it can be a overkill for many projects.
But with flask you can go either way. Write reusable apps or write simple apps. Check these cookiecutter skeletons -
minimal skeleton
myproject
├── config.py
├── instance
│   └── config.py
├── myproject
│   ├── commands.py
│   ├── controllers.py
│   ├── extensions.py
│   ├── forms.py
│   ├── __init__.py
│   ├── models.py
│   ├── routes.py
│   └── ui
│   ├── static
│   │   ├── css
│   │   │   └── styles.css
│   │   └── js
│   │   └── custom.js
│   └── templates
│   └── index.html
├── README.md
├── requirements.txt
└── wsgi.py
django like skeleton
myproject
├── config.py
├── development.py
├── instance
│   └── config.py
├── myproject
│   ├── auth
│   │   ├── controllers.py
│   │   ├── forms.py
│   │   ├── __init__.py
│   │   ├── models.py
│   │   └── routes.py
│   ├── helpers
│   │   ├── controllers.py
│   │   ├── __init__.py
│   │   └── models.py
│   ├── __init__.py
│   └── ui
│   └── templates
│   ├── 404.html
│   ├── 500.html
│   └── base.html
├── README.md
├── requirements.txt
├── tests
│   ├── auth
│   │   ├── __init__.py
│   │   └── test_controllers.py
│   └── __init__.py
└── wsgi.py
This is an excellent article on this.
You could get inspired by the cookiecutter templates here to jumpstart your app development
https://github.com/imwilsonxu/fbone
https://github.com/cookiecutter-flask/cookiecutter-flask
Here is the basic file structure for flask I use regularly.
yourapp/
static/
js
css
img
templates/
home.html
index.html
app.py
static folder contains all the static files of the website.
The templates folder contains all the HTML pages.
and app.py contains your python views.
I decided to nest the source code folder under src/.
my_flask_app (project folder)
├── app.py
├── setup.py
├── src/
│ ├── my_flask_app/ (source code folder)
│ │ ├── config.py
│ │ ├── errors.py
│ │ ├── forms.py
│ │ ├── __init__.py
│ │ ├── models.py
│ │ ├── routes.py
│ │ ├── static/
│ │ └── templates/
│ └── my_flask_app.egg-info/
|
└── tests/ (test folder)
Because of this, I added package_dir={'': 'src'} in setup.py.
good idea is to goole for sceletons/template projects on github
for example you can look at this
https://github.com/xen/flask-project-template
https://github.com/upperlinecode/flaskproject
https://github.com/alisezer/flask-template
In flask we can maintain the mvc structure like as separate all thinks
for example
1 Templets folder contains all html files
2 Static folder contains all css and boostrap related files
3 User defined db folder for db connection and crud operations
4 User defined Model folder for accessing/ binding the data from Templets/front- end to db/back-end connectivity
and after the main activity file
for reference flask file structure link as follow
https://flask.palletsprojects.com/en/1.1.x/tutorial/layout/
For larger projects here's what my directory structure looks like
app_name(root folder)
│ .env
│ .gitignore
│ .gitattributes
│ README.MD
│ pyproject.toml
│
└── app(source code)
│ │ __init__.py
│ │ __main__.py
│ │ db.py
│ │ auth.py
│ │ forms.py
│ │ utils.py
│ │ config.py
│ │
│ └─── routes
│ __init__.py
│ views.py
│ api.py
│ auth.py
│
└─ resources
│ |─── static
│ │ css
│ │ js
│ │ images
│ │
│ └─── templates
│ base
| components
│
└─ tests
└─ venv
└─ docs

Categories