django入门

下载django

git clone https://github.com/django/django.git

安装

python setup.py install 

创建项目mysns

django-admin.py startproject mysns

启动服务器

在工程目录下执行:

django-admin.py startproject mysns

 创建页面views.py

vim mysns/views.py

 以下代码

1 from django.http import HttpResponse
2 def hello(request):
3     return HttpResponse("Hello world")

在urls.py文件中进行配置,注意要记得添加头文件

1 from mysns.views import hello
2 urlpatterns = patterns('',
3         (r'^hello/$', hello),

开启一个终端执行python manage.py runserver,然后在浏览器中打开http://127.0.0.1:8000/hello/,得到

如果我们要在浏览器中传入参数怎么办呢?先在urls.py中添加

(r'^index/(.)', system_info),

其中括号表示传入的参数。记得要import system_info

我们在views.py中添加如下代码接收参数(要import os):

1 def system_info(request, param):
2         path = ''
3         if param == 'p':
4                 path = os.getcwd()
5         return HttpResponse(path)

在浏览器中打开http://127.0.0.1:8000/index/p,得到

 

 下面学习用django创建模版

在工程目录下创建templates文件夹

mkdir templates

在该文件夹下创建文件index.html,写入代码

<title>newsns -by django</title>
<h1><font color=#{{color}}>Django, my first django program.</font></h1>

修改app目录下的settings.py文件,添加如下代码:

import os

ROOT_DIR = os.getcwd()

将模版路径添加到TEMPLATE_DIRS 

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    ROOT_DIR + '/templates'
)

在app目录下创建views.py文件,添加如下代码:

1 from django.shortcuts import render_to_response
2 def index(request,color):
3         return render_to_response('index.html', {'color':color})

编辑app目录下的urls.py文件,加入如下代码

 1 urlpatterns = patterns('',
 2     # Examples:
 3     # url(r'^$', 'newsns.views.home', name='home'),
 4     # url(r'^newsns/', include('newsns.foo.urls')),
 5 
 6     # Uncomment the admin/doc line below to enable admin documentation:
 7     # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
 8 
 9     # Uncomment the next line to enable the admin:
10     # url(r'^admin/', include(admin.site.urls)),
11     (r'^index/(d{1,9})$', index),
12 )

在浏览器中打开http://127.0.0.1:8000/index/1,得到

模版创建成功。

原文地址:https://www.cnblogs.com/goodhacker/p/3219435.html