django+mysql實現網頁查詢


django+mysql實現網頁查詢

實現網頁查詢並返回結果,將查詢關鍵字保存至數據庫

環境:

  • vscode 編輯器
  • python3.8.2
  • djangoVersion: 2.0
  • pip list
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>

  • 命令行檢查django是否安裝成功

    python manage.py runserver

3、數據庫mysql安裝

  • https://www.cnblogs.com/winton-nfs/p/11524007.html

  • 下載mysql安裝包,解壓到安裝目錄,注意目錄不要包含中文

  • ①下轉到mysql的bin目錄下:cmd命令行:cd mysql..\bin

  • ②安裝mysql的服務:mysqld --install 或者mysqld –remove ,mysqld remove MySQL,刪除data文件夾

  • ③初始化mysql,在這里,初始化會產生一個隨機密碼,記住這個密碼,后面會用到(mysqld --initialize --console)

    • mysqld --initialize --console
    • -Knhlwhhj1wV
  • ④開啟mysql的服務(net start mysql)、停服務net stop mysql

  • ⑤登錄驗證,mysql是否安裝成功!

    • mysql -u root -p 密碼提示輸入:root110
  • 修改密碼:alter user 'root'@'localhost' identified by 'root110';

    • exit
    • mysql -u root -p 密碼提示輸入:root110
  • 設置系統的全局變量:

    • ①點擊"我的電腦"-->"屬性"-->''高級系統設置''-->''環境變量''

4、navicat 連接數據庫

  • 創建連接
    • mysql
    • app_mysql
    • localhost
    • 3306
    • root
    • root110
  • 創建數據庫
    • 數據庫名:mysql-demo1
    • 字符集:utf8mb4
    • 排序規則:空着
  • 創建表shop,text
    • shop表 和 text表可使用語法生成

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、測試結果

  • python manage.py runserver
  • 網頁打開http://127.0.0.1:8000/
  • 輸入表單內容,並提交
  • 跳轉到http://127.0.0.1:8000/handle並有數據返回
  • 查看Navicat數據庫中text表中是否保存有關鍵字

10、相關問題

  • 提示需要安裝更高版本的mysqlclient時,可考慮降低django版本,原因可baidu

  • 提示vscode會提示出現Class “xxx” has no ‘objects’ member錯誤:

    • 不影響使用
    • pip install pylint-django
  • settings.json中增加以下語句

    {
        "python.pythonPath": ".venv\\Scripts\\python.exe",
        "python.linting.pylintArgs": ["--generate-members"]
    }
    

完整代碼

app_mysql

  • views.py
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接收
  • 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'),
]
  • modles.py
# 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'

  • service.py
from .models import Text

## 存儲到數據庫功能的文件
def addText(text):
    text1 = Text(text=text)
    text1.save()
  • seach.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>
  • 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>
    {% for i  in resp %}
    <h1>{{ i }}</h1>
    {% endfor%}
</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM