Django笔记-1

一、Django安装

  1. pip 安装
   (sudo) pip install django
  1. 下载源码安装
    (sudo) python  setup.py install

二、创建Django工程

      > django-admin.py startproject prjoect-name

三、Django目录

urls.py
  请求的url配置,关联对应的views.py中的一个函数。访问url对应一个处理函数。
views.py
  处理用户发出的请求,url对应的处理函数。通过渲染templates中的页面显示内容。
models.py
  与数据库关联操作的模型类。
templates文件夹
  veiws.py中函数渲染的模板页面。
settings.py
   Django的设置、配置文件,如数据库,Debug等。
forms.py
  提供的表单类,与模型类似,用于数据验证、提交,在页面和处理view中传递数据。(类似struts1.x中的ActionForm)
admin.py
  后台设置配置文件。包括用户管理,models管理。

Django笔记-1_第1张图片
Django笔记-1_第2张图片
Django笔记-1_第3张图片

四、视图和URL配置

url配置(正则表达式):

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

urlpatterns = [
    url(r'^index/','test2.view.index'),
    url(r'^admin/', admin.site.urls),
    url(r'^add/', 'test2.view.add'),
    url(r'^$', 'test2.view.home', name='home'),  
]

视图(views.py)定义一个处理请求的函数:

from django.shortcuts import render

from django.http import HttpResponse

def index(request):

    return HttpResponse('hello world!')

def home(request):
    string = u'欢迎,小强。。。'
    #home.html是模板,string是向模板传递的参数
    return render(request,'home.html',{'string':string})
    

五、模板

使用模板使展现和逻辑处理分离。
默认配置,Django的模板系统会自动找到app下面的templates文件夹中的模板文件。
模板可使用循环,条件判断,标签及过滤器。

六、模型与数据库

在django1.9之前,数据库同步只需要一条命令:
Python manage.py syncdb

django1.9的数据库同步方法:
1、建好model
2、在项目根目录运行 python manage.py makemigrations appname,appname你的应用的名字
3、运行 python manage.py migrate

django1.9

python manage.py createsuperuser

如果是sqlite数据库,使用命令行查看表

>sqlite3  db.sqlite3  ##进入sqlite数据库
>.tables  ##查看表
>select * from test2.person;  ##分号结尾,查看表数据

你可能感兴趣的:(Django笔记-1)