django+mysql实现网页查询

时间:2020-07-05 21:34:49   收藏:0   阅读:52

django+mysql实现网页查询

实现网页查询并返回结果,将查询关键字保存至数据库

环境:

Package           Version
----------------- -------
astroid           2.4.2
colorama          0.4.3
Django            2.0
isort             4.3.21
lazy-object-proxy 1.4.3
mccabe            0.6.1
pip               20.1.1
pylint            2.5.3
PyMySQL           0.9.3
pytz              2020.1
setuptools        41.2.0
six               1.15.0
toml              0.10.1
wrapt             1.12.1

1、创建视图,添加映射

mkdir projects
cd projects
python -m venv .venv_mysql
cd .venv_mysql/scripts
activate ## 激活虚拟环境
pip install django==2.0## 高版本不支持pymysql,如果能安装上mysqlclient也可以使用高版本的
django-admin startproject  pro_mysql
cd pro_mysql
python manage.py startapp app_mysql

## 1、创建两个视图app_mysql/views.py
from django.shortcuts import render
# Create your views here.
def search(request):
    return render(request,"app_mysql/search.html",{})
def handle(request):
    return render(request,"app_mysql/resp.html",{})

## 2、修改pro/setting.py
INSTALLED_APPS = [
    ‘django.contrib.admin‘,
    ‘django.contrib.auth‘,
    ‘django.contrib.contenttypes‘,
    ‘django.contrib.sessions‘,
    ‘django.contrib.messages‘,
    ‘django.contrib.staticfiles‘,
    ‘app_mysql‘,
]

# 3、添加映射
## 3.1 子路由app/urls.py
from django.contrib import admin
from django.urls import path
from . import views
app_name = ‘app_mysql‘  ## 命名空间
urlpatterns = [
    path(‘‘, views.search,name=‘search‘),
    path(‘handle/‘, views.handle,name=‘handle‘),
]
## 3.2 总路由pro/urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
    path(‘admin/‘, admin.site.urls),
    path(‘‘, include(‘app_mysql.urls‘)),
]

2、添加页面框架并测试django

# 1、app_mysql/templates/app_mysql/search.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>搜索</title>
</head>
<body>
    <h1>hello world</h1>
    
</body>
</html>
# 2、app_mysql/templates/app_mysql/resp.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>返回内容</title>
</head>
<body>
    
</body>
</html>

3、数据库mysql安装

4、navicat 连接数据库

5、vscode设置数据库连接

## 设置pro_mysql/__init__.py
## 命令行先安装pymysql
pip install pymysql
# import pymysql  # 导入第三方模块,用来操作mysql数据库
import pymysql
pymysql.install_as_MySQLdb()

## 设置pro_mysql/settings.py
DATABASES = {
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.mysql‘,
        ‘NAME‘: ‘mysql-demo1‘,
        ‘HOST‘: ‘127.0.0.1‘,
        ‘PORT‘: 3306,
        ‘USER‘:‘root‘,
        ‘PASSWORD‘:‘root110‘
    }
}


## 命令行查看数据库细节
python manage.py inspectdb

## 生成models.py文件
python manage.py inspectdb > models.py

## 将models.py移动到app下
## 修改models.py为可写
    class Meta:
        managed = True  ## True为可写
        db_table = ‘text‘

6、搜索网页内容编写

## 1、编写app/template/name1/search.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>搜索</title>
</head>
<body>
    <form action="{% url ‘app_mysql:handle‘ %}" method="POST">    <!--命名空间app_name的值:对应函数-->
        {% csrf_token %}                                          <!--django防范跨越攻击的作用-->
        <div>       <!--搜索框-->
            <input type="text" name="搜索内容">   ## 注意属性之间没有逗号
            <input type="submit" value="搜索">
        </div>
    </form>
</body>
</html>

7、接收数据,返回数据

## 1、app_mysql/views.py中编写接收数据函数,将数据保存到数据库
from . import service
def handle(request):
    text = request.POST["搜索内容"]   ## 对应search.html中<input type="text",name="搜索内容">
    service.addText(text)            ## 将搜索的值存入数据库
## app_mysql/service.py 新建文件,存储到数据库功能的文件
from .models import Text
def addText(text):
    text1 = Text(text=text)
    text1.save()

## 2、返回数据函数
def handle(request):
    text = request.POST["搜索内容"]   ## 对应search.html中<input type="text",name="搜索内容">
    service.addText(text)            ## 将搜索的值存入数据库
    db = Shop.objects.all()          ## 将数据库的每条数据内容变为可操作的对象
    po_list=[]                        ## 创建列表
    for i in db:
        if text in i.title:
            po_list.append(i.content)       ## 若传入的text值在shop.title中,将shop.content加入列表

    return render(request,"app_mysql/resp.html",{"resp":po_list})  ## 将列表值返回给resp.html,使用resp接收

8、搜索结果返回网页编写

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>返回内容</title>
</head>
<body>
    {% for i  in resp %}
    <h1>{{ i }}</h1>
    {% endfor%}
</body>
</html>

9、测试结果

10、相关问题

完整代码

app_mysql

from django.shortcuts import render
from . import service
from app_mysql.models import Shop

# Create your views here.
from django.shortcuts import render
# Create your views here.
def search(request):
    return render(request,"app_mysql/search.html",{})

def handle(request):
    text = request.POST["搜索内容"]   ## 对应search.html中<input type="text",name="搜索内容">
    service.addText(text)            ## 将搜索的值存入数据库

    db = Shop.objects.all()          ## 将数据库的每条数据内容变为可操作的对象
    po_list=[]                        ## 创建列表
    for i in db:
        if text in i.title:
            po_list.append(i.content)       ## 若传入的text值在shop.title中,将shop.content加入列表

    return render(request,"app_mysql/resp.html",{"resp":po_list})  ## 将列表值返回给resp.html,使用resp接收
from django.contrib import admin
from django.urls import path
from . import views

app_name = ‘app_mysql‘  ## 命名空间
urlpatterns = [
    path(‘‘, views.search,name=‘search‘),
    path(‘handle/‘, views.handle,name=‘handle‘),
]
# This is an auto-generated Django model module.
# You‘ll have to do the following manually to clean this up:
#   * Rearrange models‘ order
#   * Make sure each model has one field with primary_key=True
#   * Make sure each ForeignKey has `on_delete` set to the desired behavior.
#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don‘t rename db_table values or field names.
from django.db import models


class Shop(models.Model):
    id = models.IntegerField(primary_key=True)
    title = models.CharField(max_length=255, blank=True, null=True)
    content = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = True
        db_table = ‘shop‘


class Text(models.Model):
    id = models.IntegerField(primary_key=True)
    text = models.TextField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = ‘text‘

from .models import Text

## 存储到数据库功能的文件
def addText(text):
    text1 = Text(text=text)
    text1.save()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>搜索</title>
</head>
<body>
    <form action="{% url ‘app_mysql:handle‘ %}" method="POST">    <!--命名空间app_name的值:对应函数-->
        {% csrf_token %}                                          <!--django防范跨越攻击的作用-->
        <div>       <!--搜索框-->
            <input type="text" name="搜索内容">
            <input type="submit" value="搜索">
        </div>
    </form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>返回内容</title>
</head>
<body>
    {% for i  in resp %}
    <h1>{{ i }}</h1>
    {% endfor%}
</body>
</html>
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!