django 入门实例

1. django安装

pip3 install django

2. django项目构建

django-admin startproject myapp # 创建项目
cd myapp
python manage.py startapp myweb # 创建应用

如果django-admin命令不可用,请把python安装目录下的Scripts文件加入环境变量,然后重启终端

目录结构

 

3. django模型搭建

配置数据库

/myapp/myapp/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # 使用的数据库类型,这里使用的是mysql
        'NAME': 'test', #  数据库名称
        'USER': 'root', # 账号
        'PASSWORD': '', # 密码
        'HOST': 'localhost', # 数据库地址
        'PORT': '3306', # 数据库使用的端口
    }
}

/myapp/myweb/models.py

from django.db import models

# Create your models here.
# 创建一个user表
class Users(models.Model):
    name = models.CharField(max_length=30) # 创建一个长度最大为30的字符字段  字段名:name
    age = models.IntegerField() # 创建一个整型字段  字段名:age

# 构建数据库

python manage.py migrate

 # 模型发生改变时需要执行该命令重新构建

python manage.py makemigrations

# 错误

RuntimeError: Model class myweb.models.Users doesn't declare an explicit app_lab
el and isn't in an application in INSTALLED_APPS.

# 解决方式

/myapp/myapp/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myweb', # 添加应用接口
]

# 重新构建

python manage.py makemigrations
python manage.py migrate

 

4. django 模板

/myapp/myapp/settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['myweb/templates'],  # 添加模板文件目录路径
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

模板文件

/myapp/myweb/templates/index.html

<html>

<head>
    <title>test</title>
    <meta charset="utf-8" />
</head>

<body>
    <h1>{{content}}</h1>
</body>

</html>

5. django 视图逻辑

/myapp/myweb/views.py

from django.shortcuts import render
from myweb.models import Users
from django.core import serializers

# Create your views here.
def index(request):
    results =   serializers.serialize('json',Users.objects.all()) # 查询users表的所有数据且把数据转换成json字符串输出到页面
    return render( request,'index.html',{'content':results} )

6. djangos urls配置

/myapp/myapp/urls.py

from django.conf.urls import url
from django.contrib import admin
from myweb import views as indexs

urlpatterns = [
    url(r'', indexs.index),  # 映射路由与视图关系
]

7. 启动服务器

python manage.py runserver

访问 http://127.0.0.1:8000

实例地址 https://github.com/DudeYouth/python-demo.git

posted @ 2017-06-28 14:43  Ricky_boke  阅读(2059)  评论(0编辑  收藏