Django is a Python framework that makes it easier to create web sites using Python.
Django takes care of the difficult stuff so that you can concentrate on building your
web applications.
Django emphasizes reusability of components, also referred to as DRY (Don't Repeat
Yourself), and comes with ready-to-use features like login system, database connection and
CRUD operations (Create Read Update Delete).
Django
Django is especially helpful for database driven websites.
How does Django Work? Django follows the MVT design pattern (Model View Template).
Model - The data you want to present, usually data from a database. View - A
request handler that returns the relevant template and content - based on the request from the
user.
Template - A text file (like an HTML file) containing the layout of the web page, with
logic on how to display the data.
Model
The model provides data from the database.
In Django, the data is delivered as an Object Relational Mapping (ORM), which is a
technique designed to make it easier to work with databases.
The most common way to
extract data from a database is SQL. One problem
with SQL is that you have to have a pretty good understanding of the database structure to be
able to work with it.
Django, with ORM, makes it easier to communicate with the database, without having to
write complex SQL statements.
The models are usually located in a file called models.py.
View
A view is a function or method that takes http requests as arguments, imports the relevant
model(s), and finds out what data to send to the template, and returns the final result. The
views are usually located in a file called
views.py.
Template
A template is a file where you describe how the result should be represented.
Templates are often .html files, with HTML code describing the layout of a web page, but it
can also be in other file formats to present other results, but we will concentrate on .html
files.
URLs
Django also provides a way to navigate around the different pages in a website.
When a user requests a URL, Django decides which view it will send it to. This is done
in a file called urls.py.
Create Virtual Environment
Create Virtual Environment
Virtual Environment It is suggested to have a dedicated virtual environment for each Django
project, and one way to manage a virtual environment is venv, which is included in Python.
The name of the virtual environment is your choice, in this tutorial we will call it
myworld.
Type the following in the command prompt, remember to navigate to where you want to
create your project
virtualenv env
activate the environment
./env/Scripts/activate
Installation of Django
py -m pip install Django
Check Django Version
django-admin --version
Create Requirements (Create a requirements.txt)
py -m pip freeze > requirements.txt
install requirements.txt
pip install -r requirements.txt
Create django project
django-admin startproject my_project
Go in the project
cd my_project
Run the Django Project
python manage.py runserver
Create Migrate
py manage.py makemigrations
Migrate changes
py manage.py migrate
open a Python shell
py manage.py shell
Django Create App
Django Create App
What is an App? An app is a web application that has a specific meaning in your project, like a
home page, a contact form, or a members database. In this tutorial we will create an app that
allows us to list and register members in a database. But first,
let's just create a simple Django app that displays "Hello World!".
python manage.py startapp app_name
Django Views
Django Views
Views Django views are Python functions that takes http requests and returns http response,
like HTML documents.
A web page that uses Django is full of views with different tasks and missions.
Views are usually put in a file called views.py located on your app's folder.
There is a views.py in your app folder
views.py
from django.shortcuts import render
from django.http import HttpResponse
def members(request):
return HttpResponse("Hello world!")
Django URLs
Django URLs
URLs Create a file named urls.py in the same folder as the views.py file, and type this code
in it
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('app_name.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
View SQL
View SQL
As a side-note: you can view the SQL statement that were executed from the migration above. All
you have to do is to run this command, with the migration number
py manage.py sqlmigrate app_name migrate_number
Django Models
Django Models
A Django model is a table in your database.
Django Models Up until now in this tutorial, output has been static data from
Python or HTML templates.
Now we will see how Django allows us to work with data, without having to change or
upload files in the prosess.
In Django, data is created in objects, called Models, and is actually tables in a
database.
Create Table (Model) To create a model, navigate to the models.py file in the
/members/ folder.
Open it, and add a Member table by creating a Member class, and describe the table
fields in it
from django.db import models
class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
run our application by using apache server
run our application by using apache
server
if we want to run our application by using apache server rather than built-in development
server, we need to configure apache2.conf file located at /etc/apache directory. Add the
following code into this file.
After adding these lines, restart apache server by using the service apache2 restart
command and then type localhost to the browser's address bar. This time, project will run on
apache server rather than a built-in server. See, it shows the home page of the application.
The MVT (Model View Template) is a software design pattern. It is a collection of three
important components Model View and Template. The Model helps to handle database. It is a data
access layer which handles the data.
The Template is a presentation layer which handles User Interface part completely. The View is
used to execute the business logic and interact with a model to carry data and renders a
template.
Although Django follows MVC pattern but maintains it?s own conventions. So, control is handled
by the framework itself.
There is no separate controller and complete application is based on Model View and Template.
That?s why it is called MVT application.
Here, a user requests for a resource to the Django, Django works as a controller and check to
the available resource in URL.
If URL maps, a view is called that interact with model and template, it renders a template.
Django responds back to the user and sends a template as a response.
Django Model Fields
Django Model Fields
The fields defined inside the Model class are the columns name of the mapped table. The fields
name should not be python reserve words like clean, save or delete etc.
Django provides various built-in fields types.
Field Name
Class
Particular
AutoField
class AutoField(**options)
It An IntegerField that automatically increments.
BigAutoField
class BigAutoField(**options)
It is a 64-bit integer, much like an AutoField except that it is guaranteed to
fit numbers from 1 to 9223372036854775807.
BigIntegerField
class BigIntegerField(**options)
It is a 64-bit integer, much like an IntegerField except that it is guaranteed
to fit numbers from -9223372036854775808 to 9223372036854775807.
BinaryField
class BinaryField(**options)
A field to store raw binary data.
BooleanField
class BooleanField(**options)
A true/false field.
The default form widget for this field is a CheckboxInput.
CharField
class DateField(auto_now=False, auto_now_add=False, **options)
It is a date, represented in Python by a datetime.date instance.
DateTimeField
class DateTimeField(auto_now=False, auto_now_add=False, **options)
It is a date, represented in Python by a datetime.date instance.
DateTimeField
class DateTimeField(auto_now=False, auto_now_add=False, **options)
It is used for date and time, represented in Python by a datetime.datetime
instance.
DecimalField
class DecimalField(max_digits=None, decimal_places=None, **options)
It is a fixed-precision decimal number, represented in Python by a Decimal
instance.
DurationField
class DurationField(**options)
A field for storing periods of time.
EmailField
class EmailField(max_length=254, **options)
It is a CharField that checks that the value is a valid email address.
FileField
class FileField(upload_to=None, max_length=100, **options)
It is a file-upload field.
FloatField
class FloatField(**options)
It is a floating-point number represented in Python by a float instance.
ImageField
class ImageField(upload_to=None, height_field=None, width_field=None,
max_length=100, **options)
It inherits all attributes and methods from FileField, but also validates that
the uploaded object is a valid image.
IntegerField
class IntegerField(**options)
It is an integer field. Values from -2147483648 to 2147483647 are safe in all
databases supported by Django.
NullBooleanField
class NullBooleanField(**options)
Like a BooleanField, but allows NULL as one of the options.
PositiveIntegerField
class PositiveIntegerField(**options)
Like an IntegerField, but must be either positive or zero (0). Values from 0 to
2147483647 are safe in all databases supported by Django.
SmallIntegerField
class SmallIntegerField(**options)
It is like an IntegerField, but only allows values under a certain
(database-dependent) point.
TextField
class TextField(**options)
A large text field. The default form widget for this field is a Textarea.
TimeField
class TimeField(auto_now=False, auto_now_add=False, **options)
A time, represented in Python by a datetime.time instance.
Field Options
Field Options
Each field requires some arguments that are used to set column attributes. For example,
CharField requires mac_length to specify varchar database.
Common arguments available to all field types. All are optional
Field Options
Particulars
Null
Django will store empty values as NULL in the database.
Blank
It is used to allowed field to be blank.
Choices
An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
field.
Default
The default value for the field. This can be a value or a callable object.
help_text
Extra "help" text to be displayed with the form widget. It's useful for
documentation even if your field isn't used on a form.
primary_key
This field is the primary key for the model.
Unique
This field must be unique throughout the table.
Django Insert Data
Django Insert Data
Add Records The Members table created in the previous chapter is empty. We will use the Python
interpreter (Python shell) to add some members to it.
py manage.py shell
from members.models import Member
Member.objects.all()
Output:<QuerySet []> A QuerySet is a collection of data from a database.
member = Member(firstname='Emil', lastname='Refsnes')
Update Records To update records that are already in the database, we first have to get the
record we want to update
from members.models import Member
x = Member.objects.all()[4]
x will now represent the member at index 4
x.firstname = "Stalikken"
x.save()
Django Delete Data
Django Delete Data
Delete Records To delete a record in a table, start by getting the record you want to delete
from members.models import Member
x = Member.objects.all()[4]
x will now represent the member at index 4
x.delete()
Django Update Model
Django Update Model
Add Fields in the Model To add a field to a table after it is created, open the models.py
file, and make your changes
from django.db import models
class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
phone = models.IntegerField(null=True)
joined_date = models.DateField(null=True)
email = models.EmailField(max_length=50)
age = models.IntegerField()
py manage.py shell
from members.models import Member
x = Member.objects.all()[0]
x.phone = 5551234
x.joined_date = '2022-01-05'
x.save()
various built-in error classes in views
various built-in error classes in views
Class
Description
class HttpResponseNotModified
It is used to designate that a page hasn't been modified since the user's last
request (status code 304).
class HttpResponseBadRequest
It acts just like HttpResponse but uses a 400 status code.
class HttpResponseNotFound
It acts just like HttpResponse but uses a 404 status code.
class HttpResponseNotAllowed
It acts just like HttpResponse but uses a 410 status code.
HttpResponseServerError
It acts just like HttpResponse but uses a 500 status code.
Django Http Decorator
Django Http Decorator
These decorators are listed in django.views.decorators.http and return a
django.http.HttpResponseNotAllowed if the conditions are not met.
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse, HttpResponseNotFound
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET"])
def show(request):
return HttpResponse('<h1>This is Http GET request.</h1>')
Django URL Functions
Django URL Functions
Name
Description
Example
path(route, view, kwargs=None, name=None)
It returns an element for inclusion in urlpatterns.
path('index/', views.index, name='main-view')
re_path(route, view, kwargs=None, name=None)
It returns an element for inclusion in urlpatterns.
re_path(r'^index/$', views.index, name='index'),
include(module, namespace=None)
It is a function that takes a full Python import path to another URLconf module
that should be "included" in this place.
register_converter(converter, type_name)
It is used for registering a converter for use in path() routes.
Django Static Files Handling
Django Static Files Handling
In a web application, apart from business logic and data handling, we also need to handle and
manage static resources like CSS, JavaScript, images etc.
It is important to manage these resources so that it does not affect our application
performance.
Django deals with it very efficiently and provides a convenient manner to use resources.
The django.contrib.staticfiles module helps to manage them
1. Include the django.contrib.staticfiles in INSTALLED_APPS.
5. Store all images, JavaScript, CSS files in a static folder of the application. First create a
directory static, store the files inside it.
Django - Sending E-mails
Django - Sending E-mails
Django comes with a ready and easy-to-use light engine to send e-mail. Similar to Python you
just need an import of smtplib. In Django you just need to import django.core.mail. To start
sending e-mail, edit your project settings.py file and set the following options :
EMAIL_HOST − smtp server.
EMAIL_HOST_USER − Login credential for the smtp server.
EMAIL_HOST_PASSWORD − Password credential for the smtp server.
EMAIL_PORT − smtp server port.
EMAIL_USE_TLS or _SSL − True if secure connection.
Parameters details for the EmailMessage class creation −
Subject − E-mail subject.
message − E-mail body in HTML.
from_email − E-mail from.
to − List of receivers’ e-mail address.
bcc − List of “Bcc” receivers’ e-mail address.
connection − E-mail backend.
from django.core.mail import EmailMessage
from django.http import HttpResponse
def sendHTMLEmail(request , emailto):
html_content = "<strong>Comment tu vas?</strong>"
email = EmailMessage("my subject", html_content, "paul@polo.com", [emailto])
email.content_subtype = "html"
res = email.send()
return HttpResponse('%s'%res)
Django - Cookies Handling
Django - Cookies Handling
cookies are saved on the client side and depending on your client browser security level,
setting cookies can at times work and at times might not.
To illustrate cookies handling in Django, let's create a system using the login system we
created before. The system will keep you logged in for X minute of time, and beyond that time,
you will be out of the app.
For this, you will need to set up two cookies, last_connection and username.
setting cookie is done by the set_cookie method called on the response not the request, and also
note that all cookies values are returned as string.
from django.template import RequestContext
def login(request):
username = "not logged in"
if request.method == "POST":
#Get the posted form
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
username = MyLoginForm.cleaned_data['username']
else:
MyLoginForm = LoginForm()
response = render_to_response(request, 'loggedin.html', {"username" : username},
context_instance = RequestContext(request))
response.set_cookie('last_connection', datetime.datetime.now())
response.set_cookie('username', datetime.datetime.now())
return response
def formView(request):
if 'username' in request.COOKIES and 'last_connection' in request.COOKIES:
username = request.COOKIES['username']
last_connection = request.COOKIES['last_connection']
last_connection_time = datetime.datetime.strptime(last_connection[:-7],
"%Y-%m-%d %H:%M:%S")
if (datetime.datetime.now() - last_connection_time).seconds < 10:
return render(request, 'loggedin.html', {"username" : username})
else:
return render(request, 'login.html', {})
else:
return render(request, 'login.html', {})
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
urlpatterns = patterns('myapp.views',
url(r'^connection/','formView', name = 'loginform'),
url(r'^login/', 'login', name = 'login'))
Django - Sessions
Django - Sessions
we can use client side cookies to store a lot of useful data for the web app. We have seen
before that we can use client side cookies to store various data useful for our web app. This
leads to lot of security holes depending on the importance of the data you want to save.
For security reasons, Django has a session framework for cookies handling. Sessions are used to
abstract the receiving and sending of cookies, data is saved on server side (like in database),
and the client side cookie just has a session ID for identification. Sessions are also useful to
avoid cases where the user browser is set to ‘not accept’ cookies.
By default, Django saves session information in database (django_session table or
collection), but you can configure the engine to store information using other ways like: in
file or in cache.
When session is enabled, every request (first argument of any view in Django) has a session
(dict) attribute.
Some More Possible Actions Using Sessions
We have seen how to store and access a session, but it's good to know that the session attribute
of the request have some other useful actions like −
set_expiry (value) − Sets the expiration time for the session.
get_expiry_age() − Returns the number of seconds until this session expires.
get_expiry_date() − Returns the date this session will expire.
clear_expired() − Removes expired sessions from the session store.
get_expire_at_browser_close() − Returns either True or False, depending on whether the user’s
session cookies have expired when the user’s web browser is closed.
def logout(request):
try:
del request.session['username']
except:
pass
return HttpResponse("You are logged out.")
Django - Caching
Django - Caching
Django comes with its own caching system that lets you save your dynamic pages, to avoid
calculating them again when needed. The good point in Django Cache framework is that you can
cache
1) The output of a specific view.
2) A part of a template.
3) Your entire site.
To use cache in Django, first thing to do is to set up where the cache will stay. The cache
framework offers different possibilities - cache can be saved in database, on file system or
directly in memory. Setting is done in the settings.py file of your project.
Ajax essentially is a combination of technologies that are integrated together to reduce the
number of page loads. We generally use Ajax to ease end-user experience. Using Ajax in Django
can be done by directly using an Ajax library like JQuery or others. Let's say you want to use
JQuery, then you need to download and serve the library on your server through Apache or others.
Then use it in your template, just like you might do while developing any Ajax-based
application.
Another way of using Ajax in Django is to use the Django Ajax framework. The most commonly used
is django-dajax which is a powerful tool to easily and super-quickly develop asynchronous
presentation logic in web applications, using Python and almost no JavaScript source code. It
supports four of the most popular Ajax frameworks: Prototype, jQuery, Dojo and MooTools.
Using Django-dajax
pip install django_dajax
Add dajax and dajaxice in your project settings.py in INSTALLED_APPS
Page Not Found If you try to access a page that does not exist (a 404 error), Django directs
you to a built-in view that handles 404 errors.
If you got the first result, you got directed to the built-in Django 404 template.
If you got the second result, then DEBUG is set to True in your settings, and you
must set it to False to get directed to the 404 template.
This is done in the settings.py file, which is located in the project folder, in
our case the my_tennis_club folder, where you also have to specify the host name from where your
project runs from
Important:
When DEBUG = False, Django requires you to specify the hosts you will allow this Django project
to run from.
In production, this should be replaced with a proper domain name:
ALLOWED_HOSTS = ['yourdomain.com']
Customize the 404 Template Django will
look for a file named 404.html in the templates folder, and display it when there is a 404
error.
If no such file exists, Django shows the "Not Found" that you saw in the example above.
To customize this message, all you have to do is to create a file in the templates
folder and name it 404.html, and fill it with write whatever you want
Add Test View
Add Test View
Test View When testing different aspects of Django, it can be a good idea to have somewhere
to test code without destroying the main project.
This is optional off course, but if
you like to follow all steps in this
tutorial, you should add a test view that is excactly like the one we create below. Then you can
follow the examples and try them out on your own computer.
Add View Start by adding a view called "testing" in the views.py file
Django Admin
Django Admin
Django Admin Django Admin is a really great tool in Django, it is actually a CRUD* user
interface of all your models!
*CRUD stands for Create Read Update Delete.
Admin - Create User
Admin - Create User
Create User To be able to log into the admin application, we need to create a user.
This is done by typing this command in the command view
py manage.py createsuperuser
Admin - Include Member
Admin - Include Member
Include Member in the Admin Interface To include the Member model in the admin interface, we
have to tell Django that this model should be visible in the admin interface.
This
is done in a file called admin.py,
and is located in your app's folder, which in our case is the members folder.
from django.contrib import admin
admin.site.register(Member)
Admin - Set Fields to Display
Admin - Set Fields to Display
Make the List Display More Reader-Friendly
When you display a Model as a list, Django
displays each record as the string representation of the record object, which in our case is
"Member object (1)", "Member object(2)"
etc.
We can control the fields to display by specifying them in in a list_display
property in the admin.py file.
First create a MemberAdmin() class and specify the list_display tuple, like this
If Statement An if statement evaluates a variable and executes a block of code if the value is
true. Elif The elif keyword says "if the previous conditions were not true, then try this
condition". Else The else keyword catches anything which isn't caught
by the preceding conditions.
> Is less than. <= Is less than, or equal to. >= Is greater than,
or equal to.
{% if greeting < 2 %}
{% endif %}
To check if more than one condition is true.
{% if greeting == 1 and day == "Friday" %}
{% endif %}
{% if greeting == 2 %}
{% endif %}
To check if one of the conditions is true.
{% if greeting == 1 or greeting == 5 %}
{% endif %}
To check if a certain item is present in an object.
{% if 'Banana' in fruits %}
{% endif %}
To check if a certain item is not present in an object.
{% if 'Banana' not in fruits %}
{% endif %}
Check if two objects are the same. This operator is different from the == operator,
because the == operator checks the values of two objects, but the is operator checks
the identity of two objects.
{% if x is y %}
{% else %}
{% endif %}
Django for Tag
Django for Tag
For Loops A for loop is used for iterating over a sequence, like looping over items in an
array, a list, or a dictionary.
Reversed
The reversed keyword is used when you want to do the loop in reversed order.
Empty
The empty keyword can be used if you want to do something special if the object is empty.
{% for x in fruits %}{% endfor %}
{% for x in members reversed %}
{% endfor %}
{% for x in emptytestobject %}
{% empty %} {% endfor %}
Loop Variables
Loop Variables
Django has some variables that are available for you inside a loop:
forloop.counter
forloop.counter0
forloop.first
forloop.last
forloop.parentloop
forloop.revcounter
forloop.revcounter0
The current iteration, starting at 1.
{% for x in fruits %} {{ forloop.counter }} {% endfor %}
The current iteration, starting at 0.
{% for x in fruits %} {{ forloop.counter0 }} {% endfor %}
Allows you to test if the loop is on its first iteration.
{% for x in fruits %}
<li
{% if forloop.first %}
style='background-color:lightblue;'
{% endif %}
>{{ x }}</li>
{% endfor %}
Allows you to test if the loop is on its last iteration.
{% for x in fruits %}
<li
{% if forloop.last %}
style='background-color:lightblue;'
{% endif %}
>{{ x }}</li>
{% endfor %}
The current iteration if you start at the end and count backwards, ending up at 1.
{% for x in fruits %}
{{ forloop.revcounter }}
{% endfor %}
The current iteration if you start at the end and count backwards, ending up at 0.
{% for x in fruits %}
{{ forloop.revcounter0 }}
{% endfor %}
Django comment Tag
Django comment Tag
Comments Comments allows you to have sections of code that should be ignored.
Comment Description You can add a message to your comment, to help you remember
why you wrote the comment, or as message to other people reading the code.
{% comment %}
{% endcomment %}
{% comment "this was the original welcome message" %}
{% endcomment %}
<h1>Welcome{# Everyone#}</h1>
Django include Tag
Django include Tag
Include The include tag allows you to include a template inside the current template.
This is useful when you have a block of content that is the same for many pages.
Variables in Include You can send variables into the template by using the with
keyword.
In the include file, you refer to the variables by using the {{ variablename }} syntax
{% include 'footer.html' %}
Variables in Include
{% include "mymenu.html" with me="TOBIAS" sponsor="W3SCHOOLS" %}
mymenu.html
<div>HOME | {{ me }} | ABOUT | FORUM | {{ sponsor }}</div>
Django QuerySet
Django QuerySet
Django QuerySet A QuerySet is a collection of data from a database.
A QuerySet is
built up as a list of objects.
QuerySets makes it easier to get the data you actually need, by allowing you to filter
and order the data at an early stage.
QuerySet - Get Data
QuerySet - Get Data
Get Data There are different methods to get data from a model into a QuerySet. The values()
Method The values() method allows you to return each object as a Python dictionary, with the
names and values as key/value pairs Return Specific Columns The values_list()
method allows you to return only the columns that you specify.
Django QuerySet - Filter
Django QuerySet - Filter
QuerySet Filter The filter() method is used to filter your search, and allows you to return
only the rows that matches the search term.
AND
The filter() method takes the arguments as **kwargs (keyword arguments), so you can filter
on more than one field by sepearting them by a comma.
OR
To return records where firstname is Emil or firstname is Tobias (meaning: returning
records that matches either query, not necessarily both) is not as easy as the AND example
above.
We can use multiple filter() methods, separated by a pipe | character. The results will
merge into one model.
Field Lookups Django has its own way of specifying SQL statements and WHERE
clauses.
To make specific where clasuses in Django, use "Field lookups".
Field lookups are keywords that represents specific SQL keywords.
In SQL, the above statement would be written like this:
SELECT * FROM members WHERE firstname = 'Emil';
Order By To sort QuerySets, Django uses the order_by() method
Descending Order
By default, the result is sorted ascending (the lowest value first), to change the
direction to descending (the highest value first), use the minus sign (NOT), - in front of the
field name
Multiple Order Bys To order by more than one field, separate the fieldnames
with a comma in the order_by() method
In SQL, the above statement would be written like this:
SELECT * FROM members ORDER BY firstname;
Create Static Folder When building web applications, you probably want to add some static
files like images or css files.
Start by creating a folder named static in your project, the same place where you
created the templates folder:
The name of the folder has to be static.
Add a CSS file in the static folder, the name is your choice, we will call it
myfirst.css
Didn't Work? Just testing? If you just want to play around, and not going to
deploy your work, you can set DEBUG = True in the settings.py file, and the example above will
work.
Plan to deploy? If you plan to deploy your work, you should set DEBUG = False in the
settings.py file. The example above will fail, because Django has no built-in solution for
serving static files, but there are other
ways to serve static files
WhiteNoise Django does not have a built-in solution for serving static files, at least not
in production when DEBUG has to be False.
We have to use a third-party solution to accomplish this.
In this Tutorial we will use WhiteNoise, which is a Python library, built for serving
static files.
Modify Settings To make Django aware of you wanting to run WhitNoise, you have
to specify it in the MIDDLEWARE list in settings.py file
Handle Static Files Static files in your project, like stylesheets,
JavaScripts, and images, are not handled automatically by Django when DEBUG = False.
When DEBUG = True, this worked fine, all we had to do was to put them in the static
folder of the application.
When DEBUG = False, static files have to be collected and put in a specified folder
before we can use it.
Collect Static Files To collect all necessary static files for your project,
start by specifying a STATIC_ROOT property in the settings.py file.
This specifies a folder where you want to collect your static files.
You can call the folder whatever you like, we will call it productionfiles
Add a Global File We have learned how to add a static file in the application's static
folder, and how to use it in the application.
But what if other applications in your project wants to use the file?
Then we have to create a folder on the root directory and put the file(s) there.
It is not enough to create a static folder in the root directory, and Django will fix
the rest. We have to tell Django where to look for these static files.
Add a CSS file in the mystaticfiles folder, the name is your choice, we will call it
myglobal.css
In the STATICFILES_DIRS list, you can list all the directories where
Django should look for static files.
The BASE_DIR keyword represents the root directory of the project, and together with
the / "mystaticfiles", it means the mystaticfiles folder in the root directory.
Search Order If you have files with the same name, Django will use the first
occurrence of the file.
The search starts in the directories listed in STATICFILES_DIRS, using the order you
have provided. Then, if the file is not found, the search continues in the static folder of each
application.
Modify the Template Now you have a global CSS file for the entire project, which
can be accessed from all your applications.
To use it in a template, use the same syntax as you did for the myfirst.css file:
#Add this in your settings.py file:
STATICFILES_DIRS = [
BASE_DIR / 'mystaticfiles'
]
Provider-Specific Settings We have chosen AWS as our hosting provider, and Elastic Beanstalk as
a service to deploy the Django project, and it has some specific requirements. .ebextension
Folder It requires that you create a folder on the root level of
your project called .ebextensions Create django.config File In the .ebextensions folder, create
a file called django.config