python例子-开始一个Django项目

一、创建项目:

django-admin startproject mysite

二、到该目录下,创建app:

python manage.py startapp learn # learn 是一个app的名称

并将app添加到mysite/mysite/settings.py 中:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
 
    'learn',
)

三、定义处理请求的函数:

在文件views.py中定义:

#coding:utf-8
from django.http import HttpResponse
 
def index(request):
    return HttpResponse(u"欢迎光临 Mysite项目")

注意编码.

四、关联函数和请求:

在mysite/mysite/urls.py 中修改:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^$','learn.views.index',name='home'),
    url(r'^admin/', include(admin.site.urls)), #这一行系统默认
]

注意:url中是用正则表达式匹配URL的。name的值为处理URL的函数名,string说明了函数的路径.

五、获取请求中的参数:(url='http://localhost:8000/?a=123&b=bat')

from django.shortcuts import render
from django.http import HttpResponse
 
def add(request):        #此为处理请求的函数
    a = request.GET['a']
    b = request.GET['b']
    c = int(a)+int(b)
    return HttpResponse(str(c))

六、URL中正则的灵活运用:

eg:网站采用 http://host:80/calc/3/4/这样的方式

更改处理函数:views.py

def add2(request,a,b):
    c = int(a) + int(b)
    return HttpResponse(str(c))

更改正则表达式:urls.py

url(r'^calc/(d+)/(d+)/$', 'calc.views.add2', name='add2'),

 七、前端页面模版应用:

在app的目录下创建templates文件夹,在该文件夹下创建模版文件:home.html (Django项目默认会寻找该目录下的模版文件)

[cos@localhost templates]$ ls
ad.html  base.html  bottom.html  home.html  nav.html  tongji.html  # 这些模版是项目引用的.
[cos@localhost templates]$ cat home.html
{% extends 'base.html' %}

{% block title %}welcome home html{% endblock %}            #覆盖默认内容,否则就显示继承自base.html中的默认内容.

{% block content %}
{% include 'ad.html' %}                           #引用ad.html模版.
this is index page,welcome!
{% endblock %}

更改处理请求的函数,向客户端返回该模版文件:(当然内容是经过渲染的)

app/views.py

from django.shortcuts import render
 
def home(request):
    return render(request, 'home.html')

 八、启动项目:

[cos@localhost mysite]$ python manage.py runserver 0.0.0.0:8000
Performing system checks...

System check identified no issues (0 silenced).
October 20, 2015 - 14:31:54
Django version 1.8.5, using settings 'zqxt_tmpl.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
[20/Oct/2015 14:31:54] "GET / HTTP/1.1" 500 126680
[20/Oct/2015 14:32:07] "GET / HTTP/1.1" 500 129469
[20/Oct/2015 14:33:37] "GET / HTTP/1.1" 200 280
原文地址:https://www.cnblogs.com/xccnblogs/p/4896531.html