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 不是內(nèi)部或外部命令.
首先,找到python安裝的實(shí)際路徑(哪個(gè)文件夾)。現(xiàn)在我假設(shè)你的python安裝在C:\Python25目錄下羹与,設(shè)置環(huán)境變量方法如下:
方法一:我的電腦->屬性->高級(jí)->環(huán)境變量->系統(tǒng)變量
在系統(tǒng)變量里找到PATH饭于,雙擊PATH毯辅,在結(jié)尾加上 ";C:\Python25"(不要引號(hào))
這個(gè)方法對(duì)我無(wú)效梦谜!
方法二:運(yùn)行->cmd
輸入set PATH=%PATH%;C:\Python25
接下來(lái)潦牛,再在當(dāng)前的 cmd下輸入python异希,即可運(yùn)行健盒。
這個(gè)方法對(duì)我有效!
Python命令行窗口提示“不是內(nèi)部或外部命令……”的解決方法
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.
我在實(shí)踐過(guò)程中發(fā)現(xiàn):在project目錄下的static folder里面存的文件(e.g. css files)不能夠被系統(tǒng)載入称簿。但是在各個(gè)app folder下的static folder卻可以被正確導(dǎo)入扣癣,所以實(shí)踐過(guò)程中,我實(shí)際上把所有的static files放到各個(gè)app下的static folder中憨降,然后在STATICFILES_FINDERS中定義去各個(gè)app旗下尋找static files的邏輯
另外一個(gè)不錯(cuò)的網(wǎng)友總結(jié):
c) Load static files in HTML templates
After DOCTYPE:
{% load staticfiles %}
Then at source attribute or similar:
{% static "images/django.jpg" %}