1. Create a virtual environment
A. Why suing this?
Since there are many open-sourced software packages involved in, they may depend on each other in terms of their 'versions'. The issue is that they may update in different pace and in different aspects, which causes compatibility issues. In order to manage different versions of those packages and make them work together, virtual environment is utilised. Therefore, each project should be set up in a virtual environment.
Got from the website:
Packages changes can break backwards compatibility, and if you still want to test out new features without breaking the web app, then virtual environment comes to help to make it so easy to do.
B. How to use it?
I utilized Anaconda, but ‘virtualenvwrapper’ is a very popular pick-up by others.
1). First, download and install Anaconda.
2). Then, create the virtual environement:
In the command line:
conda create --name myEnv django
- Here it created a virtual environement called 'myEnv' with the latest version of Django.
Sometimes, the default env setting is not desired, e.g. you need a newer version of package. Then you can specify by doing:
conda create --name myEnv python=3.5
- specifying python 3.5 to be utilized.
3). Activate the virtual env.
activate myEnv
or source activate myEnv
4). Other useful commands:
-
conda info --envs
- Listing all virtual environments in the current directory.
C. Debug cases
1) Issue: python 不是内部或外部命令.
首先,找到python安装的实际路径(哪个文件夹)。现在我假设你的python安装在C:\Python25目录下,设置环境变量方法如下:
方法一:我的电脑->属性->高级->环境变量->系统变量
在系统变量里找到PATH,双击PATH,在结尾加上 ";C:\Python25"(不要引号)
这个方法对我无效!
方法二:运行->cmd
输入set PATH=%PATH%;C:\Python25
接下来,再在当前的 cmd下输入python,即可运行。
这个方法对我有效!
Python命令行窗口提示“不是内部或外部命令……”的解决方法
2. Create a Django project
Firstly, make sure Django has been installed.
Then,
django-admin startproject first_project
This creates a Django directory with default files created:
-
__init__.py
- A blank Python script that let Python know this directory can be treated as a package. -
manage.py
- It will be utilised to make a lot of commands.
3. Create a App
python manage.py startapp app_name
This creates a Django app file directory, featured some followed files:
-
admin.py
- You can register your models here which Django will then use them with Django's admin interface. -
models.py
- Here you store the application's data models. -
test.py
- store test functions to test your code. -
views.py
- this is where you have functions that handle requests and return responses.
4. Edit settings.py
file
a. register newly created 'app_name'
in INSTALLED_APPS.
b. check whether it is working fine:
python manage.py runserver
- runserver will automatically check if there is any error.
5. Edit views.py
- Handle request and create HttpResponse.
a) Simple example
Firstly,
from django.http import HttpResponse
Then, define a function to 'take the request' and 'make a response'.
def index(request):
return HttpResponse("Hello World!")
6. Edit urls.py
to map the URL with the corresponding view function.
a) Import the views functions
from app_name import views
b) Map URL with the view function:
url(r'^$', views.function_name, name = 'function_name')
c) Using include( )
function - link to app's own urls.py
Why to use include( ) function?
For large projects, this will keep the parent urls.py file concise and clean. The whole idea behind this is to make the project modular, and app can be easily plugged-in and out. For example, if we want to install a new app, we only need to add two one line of code in the project urls.py file, instead of listing all the url patterns and their corresponding view functions.
Implementation code:
Under project urls.py
file:
from django.conf.urls import include
url(r'^app_name/', include('app_name.urls')),
Create and edit urls.py
file in corresponding app folder:
from django.conf.urls import url
from app_name import views
urlpatterns = [...]
7. Django Template
Creating 'static' HTML file with template tag defined dynamic contents, then editing the DIR key inside of the TEMPLATES dictionary in the settings.py file.
a) Create a 'templates' folder under the parent project folder.
create another app folder under the templates folder to seperate template files for each app. Again, this makes the project modular.
b) Add templates directory path in settings.py
file
This step makes Django know of the templates for the project.
DIR key requires a "hard-coded" path, which is determined by the local machined used. In order to make the Django project to be easily transferable from one computer to another, Python's os module is utilized to dynamically generate the correct file path strings, regardless of computer!
TEMPLATE_DIR = os.path.join(BASE_DIR, "templates")
Find TEMPLATES Dictionary in settings.py
file, and add TEMPLATE_DIR to key 'DIRS'.
c) Create and edit template file, e.g. index.html
This step adds variables and logics to the HTML file by using Django template tags. The backend (view functions) then will recognise the variable and insert the data from the batabase.
The variable in the template should be the same as the dictionary key passed in the view function response.
Django template tags:
{{ variable }}
{% some logics %}
d) Define a view function to handle the request and pass the data in response.
Import render( ) function:
from django.shortcuts import render
return render( ) response:
return render(request, 'app/index.html', context=dict)
- 2nd argument: specify where to load the template.
- 3rd argument: pass the data in a dictionary; variable inside template tag should be matched with the dictionary key.
8. Static files
Why using this?
Static files are images, videos, etc. They can be utilized for making up the app or adding media content.
a) Create a static folder and sub-folders (e.g. images)
b) Add static path in settings.py
.
STATIC_DIR = os.path.join(BASE_DIR, "static")
c)Add STATICFILES_DIRS and STATICFILES_FINDERS
This tells the Django where to find static files.
我在实践过程中发现:在project目录下的static folder里面存的文件(e.g. css files)不能够被系统载入。但是在各个app folder下的static folder却可以被正确导入,所以实践过程中,我实际上把所有的static files放到各个app下的static folder中,然后在STATICFILES_FINDERS中定义去各个app旗下寻找static files的逻辑
另外一个不错的网友总结:
c) Load static files in HTML templates
After DOCTYPE:
{% load staticfiles %}
Then at source attribute or similar:
{% static "images/django.jpg" %}