Django學(xué)習(xí)總結(jié) 1 - virtualenv, urls, view functions, template, static files

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.pyfile:
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.


A code example

我在實(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é):


來(lái)自于http://willdx.me/2016/04/15/Django學(xué)習(xí)筆記07_靜態(tài)文件/index.html

c) Load static files in HTML templates

After DOCTYPE:
{% load staticfiles %}
Then at source attribute or similar:
{% static "images/django.jpg" %}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末父虑,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子授药,更是在濱河造成了極大的恐慌士嚎,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,546評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件悔叽,死亡現(xiàn)場(chǎng)離奇詭異莱衩,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)娇澎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門膳殷,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人九火,你說(shuō)我怎么就攤上這事赚窃。” “怎么了岔激?”我有些...
    開(kāi)封第一講書人閱讀 164,911評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵勒极,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我虑鼎,道長(zhǎng)辱匿,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 58,737評(píng)論 1 294
  • 正文 為了忘掉前任炫彩,我火速辦了婚禮匾七,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘江兢。我一直安慰自己昨忆,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,753評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布杉允。 她就那樣靜靜地躺著邑贴,像睡著了一般席里。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上拢驾,一...
    開(kāi)封第一講書人閱讀 51,598評(píng)論 1 305
  • 那天奖磁,我揣著相機(jī)與錄音,去河邊找鬼繁疤。 笑死咖为,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的稠腊。 我是一名探鬼主播躁染,決...
    沈念sama閱讀 40,338評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼麻养!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起诺舔,我...
    開(kāi)封第一講書人閱讀 39,249評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤鳖昌,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后低飒,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體许昨,經(jīng)...
    沈念sama閱讀 45,696評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,888評(píng)論 3 336
  • 正文 我和宋清朗相戀三年褥赊,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了糕档。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,013評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡拌喉,死狀恐怖速那,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情尿背,我是刑警寧澤端仰,帶...
    沈念sama閱讀 35,731評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站田藐,受9級(jí)特大地震影響荔烧,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜汽久,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,348評(píng)論 3 330
  • 文/蒙蒙 一鹤竭、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧景醇,春花似錦臀稚、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,929評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)苍碟。三九已至,卻和暖如春撮执,著一層夾襖步出監(jiān)牢的瞬間微峰,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,048評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工抒钱, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留蜓肆,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,203評(píng)論 3 370
  • 正文 我出身青樓谋币,卻偏偏與公主長(zhǎng)得像仗扬,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子蕾额,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,960評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容