Django Installation and Usage
This article covers how to install Django, create a project, understand the directory structure, configure static files, and connect to a database — everything needed to quickly set up your first Django development environment.
Installing Django
Command-line operations:
1. Create a Django project
django-admin startproject mysite (project name)
2. Start the Django project
cd mysite
python3 manage.py runserver
3. Create an app
python manage.py startapp app01
PyCharm installation:
1. New project
Select the second option "Django" in the left panel
2. Start the project
3. Create an app — same as above
Notes:
# How to make sure your computer can start a Django project normally
1. The computer name must not contain Chinese characters
2. Open only one project per PyCharm window
3. Try to avoid Chinese characters in all project file names as well
4. Use Python 3.4–3.6 where possible
(If your project reports an error, click the last error message to go to
the source code and delete the trailing comma)
# Django version notes
1.x 2.x 3.x (3.x can be ignored for now)
The difference between 1.x and 2.x is small. We mainly cover 1.x and will
point out 2.x differences where relevant.
Many companies are still on 1.8 or 1.11; some projects use 2.0.
# Installing Django
pip3 install django==1.11.22
If another version is already installed you don't need to uninstall it first —
just reinstall and it will be replaced automatically.
If you get a timeout error, it's just a network hiccup — retry the install.
Verify success: type django-admin in a terminal and check for output.
If you are using Python 3.7+, install Django 1.17+ to avoid startup failures.Django Directory Structure
Main files explained:
- mysite/ Top-level project folder
- mysite/ Inner package folder
- settings.py Configuration file
- urls.py URL-to-view mapping (routing layer)
- wsgi.py wsgiref module entry (not usually touched)
- manage.py Django entry point
- db.sqlite3 Django's built-in SQLite3 database (lightweight, limited features)
- app01/ Application folder
- admin.py Django admin configuration
- apps.py App registration
- migrations/ Database migration records
- models.py Database models (ORM)
- tests.py Test file
- views.py View functions (view layer)Django Apps
Django is a web framework designed specifically for building apps.
The Django framework is like a university; apps are the individual colleges within it.
Each app is an independent functional module.
Any app you create must be registered in the configuration file — Django won't
recognize it otherwise.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config', # full form
'app01', # short form
]
Note: When creating a project in PyCharm, PyCharm can create one app for you and
register it automatically.When Django creates an app, the full-form entry looks like this:

Django’s Three Essential Functions
# views.py
from django.shortcuts import HttpResponse, render, redirect
# HttpResponse — return a plain string response
return HttpResponse('some string')
# render — return an HTML file
return render(request, 'login.html')
# redirect — perform a redirect
return redirect('https://www.example.com/')
return redirect('/home/')
# urls.py
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', views.index)
]
# views.py — passing data to a template
def ab_render(request):
# View functions must accept a positional parameter named request
user_dict = {'username': 'jason', 'age': 18}
# Method 1: more precise, saves resources
# return render(request, '01 ab_render.html', {'data': user_dict, 'date': 123})
# Method 2: use when you have many variables to pass
"""locals() passes every name in the current scope to the HTML page"""
return render(request, '01 ab_render.html', locals())
# Disable automatic trailing slash in settings.py
APPEND_SLASH = False
# Every view function must return an HttpResponseStatic File Configuration
By default, HTML files are placed in the templates folder.
Static files used by the website are placed in the static folder.
What are static files?
Files that have already been written on the frontend and can be used directly:
JavaScript, CSS, images, third-party frontend frameworks, etc.
Django does not create the static folder automatically — you must create it manually.
It is common practice to organize the static folder further:
- static/
- js/
- css/
- img/
- (other third-party files)
Accessing a resource via URL in the browser works only because the backend has
opened an interface for that resource. If a resource cannot be found, the backend
has not exposed an interface for it.
http://127.0.0.1:8000/static/bootstrap-3.3.7-dist/css/bootstrap.min.css
If you modify backend code but the frontend page does not update:
1. You may have opened multiple Django projects on the same port —
the first one that started is actually still running.
2. Browser cache issue:
DevTools → Settings → Network → check "Disable cache"
Static file configuration in settings.py:
STATIC_URL = '/static/' # Prefix used for static files in HTML
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"), # Static file storage path; multiple paths
# are searched in order from top to bottom
]
Dynamic static file path resolution:
{% load static %} # Similar to importing a module; loads static resources
<link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
<script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
In early development, when submitting POST requests via Django, you need to disable
the CSRF middleware in the configuration file. This middleware is Django's built-in
authentication plugin — it will be covered in detail later.
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware', <-- comment this out
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Additional notes:
Form elements default to GET:
http://127.0.0.1:8000/login/?username=jason&password=123
The form action attribute:
1. Omitted — submits to the current URL by default
2. Full URL — explicitly specifies the target
3. Path only — e.g. /login/Introduction to the request Object
request.method # Returns the request method as an uppercase string <class 'str'>
request.POST # Retrieves ordinary POST data (no files)
request.POST.get() # Gets only the last element of a list value
request.POST.getlist() # Returns the entire list
request.GET # Retrieves GET request data
request.GET.get() # Gets only the last element of a list value
request.GET.getlist() # Returns the entire list
# Example: login view
def login(request):
if request.method == 'GET':
print('GET')
return render(request, 'login.html')
if request.method == 'POST':
return HttpResponse("POST")
return render(request, 'login.html')
# Differences between GET and POST:
# GET:
# Data is carried in the URL
# Data size is limited to 2048 bytes
# More efficient than POST
# Can be bookmarked/back-navigated without losing data
# Only allows ASCII characters
#
# POST:
# All data is placed in the request body (headers)
# No data size limit
# Cannot go back — data must be re-submitted after navigating back
# No character restrictions; binary data is also allowedLast updated on