学习网址:
Django小白入门到实战教程(2021)_哔哩哔哩_bilibili
配置路由urls
创建app:在终端里输入python manage.py startapp web
python manage.py startapp web
可以看到新生成了一个名为web的app
然后我们要在setting.py中进行相关配置 (否则会报错)
'web.apps.WebConfig',
接下来我们在urls中配置相关命令
from django.contrib import admin
from django.urls import path
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('web.apps')),
]
展示html的页面
在web这个app新建一个urls文件,输入:
from django.urls import path
from . import views
urlpatterns = [
path('home/', views.home, name="home ")
]
目的:主app与前端的传参
在web下新建templates文件夹,在文件夹中新建home.html文件,
输入一段可以显示的代码段。
<!DOCTYPE html>
<html lang="en">
<body>
<text>hahahah </text>
</body>
</html>
点击右上角的运行,即可获得ip地址
点击并在后面输入/home/ ,即可获得前端页面
创建公共html模板
新建html文件,作为公共html,
输入一段显示代码
<!doctype html>
<html lang="zh-CN">
<head>
<!-- 必须的 meta 标签 -->
<title>Hello, world!</title>
</head>
<body>
</body>
</html>
在home.html中做如下修改:
{% extends 'base.html' %} # 引入文件
{% block content %}
<h1>Hello, world!</h1>
<p>检测是否可以看到我</p>
{% endblock %}
在base.html的<body>当中添加:
{% block content %}
{% endblock %}
进入网页点击刷新即可
展示导航信息
<!doctype html>
<html lang="zh-CN">
<head>
<!-- 必须的 meta 标签 -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap 的 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<title>Hello, world!</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
{% block content %}
{% endblock %}
<!-- JavaScript 文件是可选的。从以下两种建议中选择一个即可! -->
<!-- 选项 1:jQuery 和 Bootstrap 集成包(集成了 Popper) -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" ></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
<!-- 选项 2:Popper 和 Bootstrap 的 JS 插件各自独立 -->
<!--
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js" integrity="sha384-IjeXbuVdL81ilB5LykkImU8JN0WPja/i9uZAt2qjo2TnYk9NJ2MPfN3vzMH0R8n3" crossorigin="anonymous"></script>
-->
</body>
</html>
复制代码到base.html文件当中,点击刷新即可显示
接口请求
1、如果是get请求接口,并且需要带相关参数的话,可以借鉴下面的代码:
import requests
from django.http import JsonResponse
def get_info(request):
url = 'http://www.baidu.com'
params = {'id': 1, 'user': 'lin'}
response = requests.get(url=url, params=params)
return JsonResponse(response.text, safe=False)
这样将会返回一串json的字符串数据。
2、如果是post请求接口,并且需要带相关参数的话,可以借鉴下面的代码:
import requests
from json import dumps
from django.http import JsonResponse
def get_info(request):
url = 'http://www.baidu.com'
data = {'id': 1, 'user': 'lin'}
response = requests.post(url=url, data=dumps(data))
return JsonResponse(response.text, safe=False)
参考网站:(32条消息) django 使用requests请求相关接口_茕夜的博客-CSDN博客_django requests
Django ORM 实现数据的增删改查
1.创建app
python manage.py startapp app01
2.配置setting,将新建的app写入
3.写主app的urls
from django.urls import path, include
from django.contrib import admin
# from django import admin
from django.urls import path,include
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('app01.urls'))
]
4.配置app01的urls
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('add_book/', views.add_book),
]
5.__init__.py中连接MySQL数据库
# 在与 settings.py 同级目录下的 __init__.py 中引入模块和进行配置
import pymysql
pymysql.install_as_MySQLdb()
6.创建模型
在项目中的 models.py 中添加以下类:
# app01/models.py
class Book(models.Model):
id = models.AutoField(primary_key=True), # id 会自动创建,可以手动写入
title = models.CharField(max_length=32), # 书籍名称
price = models.DecimalField(max_digits=5, decimal_places=2), # 书籍价格
publish = models.CharField(max_length=32), # 出版社名称
pub_date = models.DateField() # 出版时间
然后执行以下命令
python manage.py migrate # 创建表结构
python manage.py makemigrations app01 # 让 Django 知道我们在我们的模型有一些变更
python manage.py migrate app01 # 创建表结构
过程中遇到了报错
Running migrations: No migrations to apply. Your models in app(s): 'app01' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migr ate' to apply them.
解决办法:(32条消息) Running migrations: No migrations to apply.(django不能创建数据库中的表的问题)_千寻~的博客-CSDN博客
成功显示表app01_book
一切准备就绪之后就可以进行数据的增删改查操作了。
数据的添加
# app01.views中添加
from django.shortcuts import render,HttpResponse
from app01 import models
def add_book(request):
books = models.Book.objects.create(title="如来神掌", price=200, publish="功夫出版社", pub_date="2010-10-10")
print(books, type(books)) # Book object (18)
return HttpResponse("<p>数据添加成功!</p>")
数据的查找
# app01.views中添加
from django.shortcuts import render,HttpResponse
from app01 import models
def add_book(request):
books = models.Book.objects.filter(pk=5)
print(books)
print("//")
books = models.Book.objects.filter(publish='功夫出版社', price=200)
print(books, type(books)) # QuerySet类型,类似于list。
return HttpResponse("<p>查找成功!</p>")
数据修改
from django.shortcuts import render,HttpResponse
from app01 import models
def add_book(request):
books = models.Book.objects.filter(pk__in=[7,8]).update(price=888)
return HttpResponse(books)
数据删除
from django.shortcuts import render, HttpResponse
from app01 import models
def add_book(request):
books = models.Book.objects.filter(pk__in=[1, 2]).delete()
最后感谢孟祥梅学姐的认真讲解,让我重温了django的相关属性和实例开发