Django学习总结 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 不是内部或外部命令.

首先,找到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.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

我在实践过程中发现:在project目录下的static folder里面存的文件(e.g. css files)不能够被系统载入。但是在各个app folder下的static folder却可以被正确导入,所以实践过程中,我实际上把所有的static files放到各个app下的static folder中,然后在STATICFILES_FINDERS中定义去各个app旗下寻找static files的逻辑

另外一个不错的网友总结:


来自于http://willdx.me/2016/04/15/Django学习笔记07_静态文件/index.html

c) Load static files in HTML templates

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,542评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,596评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,021评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,682评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,792评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,985评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,107评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,845评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,299评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,612评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,747评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,441评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,072评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,828评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,069评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,545评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,658评论 2 350

推荐阅读更多精彩内容