django搭建web (一)

建立工程

    django-admin.py startproject project_name

建立app

    python manage.py startapp app_name

将app添加进工程中

在工程目录下打开settings.py,在INSTALLED_APPS中,末尾添加"app_name"#app名字

在app下的views.py里定义一个业务处理函数

    def hello(request):
        return render(request,"table.html")#"table.html"模板文件 工程会自动查找app下的templates文件夹下的模板文件

模板文件与静态文件

在app文件夹下建立static文件夹,用于存储js/css/pic等静态文件
在app文件夹下建立template文件夹,用于存储template文件,如上述"hello.html"文件.

在工程目录下的urls.py定义地址

如:

    from hello import views

    ... ...

    url(r'^hello/$',views.hello,name='hello')#name是定义了一个别名 访问hello时地址跳到views.hello

加载静态文件

在app下的templates文件夹下,编辑模板文件,加载静态文件库,在最开始加入

    {% load staticfiles %}

加载静态文件

    <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">

业务处理文件views.py

在app下的views.py中 

    from django.contrib.auth.models import User

    def hello(request):
        user_list = User.objects.all()
        return render(request,"table.html",{'user_list':user_list})#将user_list以字典的方式传递到模板文件table.html

url跳转设置

在工程目录下设置urls.py

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


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^app/',include('app.urls')),
]

在app工程目录下设置urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^hello/$', views.hello, name='hello')
]

app工程目录下的views:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render

# Create your views here.

def hello(request):
	return render(request,"table.html")

其中,table.html在app目录下的templates文件夹下
只要访问app/hello即可访问table.html文件

数据更新与启动服务器

# 1. 创建更改的文件
python manage.py makemigrations
# 2. 将生成的py文件应用到数据库
python manage.py migrate
# 3.启动服务器
python manage.py runserver 8000

创建超级管理员

python manage.py createsuperuser
 
# 按照提示输入用户名和对应的密码就好了邮箱可以留空,用户名和密码必填
 
# 修改 用户密码可以用:
python manage.py changepassword username
posted @ 2017-10-22 13:25  春雨冰河  阅读(190)  评论(0编辑  收藏  举报