初识 Django

Django 是一个重量级的 Web 框架,很多成功的网站和 App 都是基于 Django 开发的。

Django 开发必备

  • Python3
  • PyCharm Community Edition

Django 使用 python 开发,推荐安装 Python3,并且使用 pip 安装 django:

pip install django

PyCharm 是用于 python 开发的 IDE,Jetbrains 出品,支持调试 python。

Django 基本操作

创建项目

Django 项目是一个模块,其特点是项目本身是一个文档夹(mysite),其中会包含一个 init.py 文档(python 模块儿的特点)。

django-admin startproject mysite

创建 App

一个 Django 项目由多个 App 组成。每个 App 也是一个 python 模块儿。

cd mysite
python manage.py startapp myapp

完成这一步后,项目的结构如下:

mysite
|__ mysite # 项目文档夹
|   |__ __init__.py
|   |__ settings.py # 主配置文档
|   |__ urls.py # url 路由文档,不同的 url 转到不同应用的 view
|   |__ wsgi.py # 网络服务器网关接口
|__ myapp # 应用文档夹
|   |__ __init__.py
|   |__ admin.py # 用于定制本应用在 Django 后台管理接口如何显示
|   |__ apps.py
|   |__ models.py # 用于定制本应用的 Model,以及在数据库中创建什么表
|   |__ tests.py
|   |__ views.py # 本应用的视图,负责页面表现
|__ manage.py # Django 管理脚本

编写路由

mysite 项目的 urls.py 文档是负责处理不同 url 的路由的,比如想要 http://127.0.0.1:8000/index/ 转向 myapp 的视图, 则需要修改 urlpatterns 为如下:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/$', views.index), # 增加了这一行,处理 index/ 路径
]

编写视图逻辑

myapp 的视图逻辑在 view.py 文档中,其中需要定义一个接受 request 的方法:

from django.shortcuts import HttpResponse

def index(request):
	return HttpResponse('Hello World!')

运行 Web 服务

python manage.py runserver 127.0.0.1:8000

这时在编辑器中输入 http://127.0.0.1:8000/index/ 就可以看到页面了。

添加 html 模板以及静态资源

在如下位置添加 static 和 templates 文档夹:

mysite
|__ mysite
|__ myapp
|__ static # 静态资源文档夹
|__ templates # html 模板文档夹
|__ manage.py

添加了以上两个文档夹后,还需要告诉 Django 去哪里找到,于是修改 settings.py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates'),
        ], # 告诉 Django 新加的 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',
            ],
        },
    },
]

....

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
] # 以及新加的 static 文档夹在哪

在 static 文档夹中添加 imgs/dog.jpg 图片,并且在 templates 文档夹中增加一个 index.html 模板文档:

<!DOCTYPE html>
<html lang="zhcn">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>
    <h1 style="background-color:#123456;color:white;">Hello World!</h1>大专栏  初识 Djangoan>
    <img src="/static/imgs/dog.jpg" />
</body>
</html>

同时修改 views.py 的 index 方法:

def index(request):
    return render(request, 'index.html')

使用数据库

使用数据库之前,首先需要在 mysite 中注册 myapp,这同样是通过修改 settings.py 实现的:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', # 注册 myapp 到 mysite
]

注册了 myapp 之后,Django 就知道给哪个 app 创建数据库表了。

然后在 models.py 中创建对应的 Model,这对应于数据库中的表:

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=32)
    desc = models.CharField(max_length=32)

上面这个例子表示会创建一个表,其中有两个字段:name 和 desc。

再运行以下命令执行创建:

python manage.py makemigrations
python manage.py migrate

使用模板

可以在 views.py 中给模板传递数据:

def index(request):
    models.DemoModel.objects.create(name='123',desc='456',age=666)
    models.DemoModel.objects.update()
    ctx = {
        'data' : models.DemoModel.objects.all()
    }
    return render(request, 'index.html', ctx)

这里给模板传递了 data 参数,这是一个字典。修改 index.html 为如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>哈哈</title>
</head>
<body>
<h1 style="background:#123456; color:#ffffff">以下是数据库信息</h1>

</body>
</html>

关于 Django 的模板语言,可以参考 https://www.runoob.com/django/django-template.html

定制 admin 页面

可以在 myapp 的 admin.py 中注册自定义的 model,这样就可以在管理员页面中进行数据库的增删操作。

from django.contrib import admin
from myapp.models import User

admin.site.register([User])

创建一个管理员账号

python manage.py createsuperuser

按照提示输入用户名、邮箱、密码即可。

参考资料

转载请注明出处:

This work is licensed under a MIT License.
原文地址:https://www.cnblogs.com/lijianming180/p/12014064.html