1.MVC模式
Web服务器开发领域里著名的MVC模式,所谓MVC就是把Web应用分为模型(M),控制器©和视图(V)三层,他们之间以一种插件式的、松耦合的方式连接在一起,模型负责业务对象与数据库的映射(ORM),视图负责与用户的交互(页面),控制器接受用户的输入调用模型和视图完成用户的请求
2.Django的MTV模式
M 代表模型(Model): 负责业务对象和数据库的关系映射(ORM)。
T 代表模板 (Template):负责如何把页面展示给用户(html)。
V 代表视图(View): 负责业务逻辑,并在适当时候调用Model和Template。
除了以上三层之外,还需要一个URL分发器,它的作用是将一个个URL的页面请求分发给不同的View处理,View再调用相应的Model和Template
3.创建模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 style="color:red;text-align:center">hello world! 我的第一个项目模板</h1>
</body>
</html>
4.提交数据
from django.http import HttpResponse #导入模块
from django.shortcuts import render
def hello(request): #第一个参数必须是request,封装了用户请求的所有内容
# HttpResponse不能直接返回字符串,必须由这个类封装起来,才能被http协议识别
# return HttpResponse("Hello world !我的第一个django项目 ")
#render 方法使用数据字典和请求元数据,渲染一个指定的html模板,
# 其多个参数中,第一个参数必须是request,第二个是模板
return render(request,'hello.html')
5.修改配置
为了让django知道我们的HTML文件(模板文件)在哪里,需要修改settings文件的相应内容
6.运行结果
再访问访问 http://127.0.0.1:8000/hello,可以看到页面:
在Django中,View的功能是对页面请求进行响应和逻辑控制,而页面内容的表示则由Django的Template模板来完成
7.数据库配置
这里添加了中文注释,所以你需要在 HelloWorld/settings.py 文件头部添加 # -- coding: UTF-8 --。
# models.py
from django.db import models
class Test(models.Model):
name = models.CharField(max_length=20)
8.创建表结构
在命令行中运行:
$ python manage.py migrate # 创建表结构
$ python manage.py makemigrations TestModel # 让 Django 知道我们在我们的模型有一些变更
$ python manage.py migrate TestModel # 创建表结构
表名组成结构为:应用名_类名(如:TestModel_test)。
报错:ImportError: cannot import name ‘render_to_response’ 解决方法
解决:使用 render 代替 render_to_response。
然后再重启服务
报错:django AttributeError: module ‘testone.search’ has no attribute ‘search_form’
解决:路由函数写错了
你可以通过命令 python manage.py createsuperuser 来创建超级用户
# python manage.py createsuperuser
Username (leave blank to use 'root'): admin
Email address: admin@runoob.com
Password:
Password (again):
Superuser created successfully.
9.登陆admin
在浏览器输入http://127.0.0.1:8000/admin,进入
目录结构如下: