Django框架 靚號管理(增刪改查)

Django框架 靚號管理(增刪改查)

在這里插入圖片描述

新建一個項目 backend

使用pycharm創建app

startapp app

項目目錄

C:\code\backend
├── app
|  ├── admin.py
|  ├── apps.py
|  ├── migrations
|  ├── models.py
|  ├── tests.py
|  ├── views.py
|  └── __init__.py
├── backend
|  ├── asgi.py
|  ├── settings.py
|  ├── urls.py
|  ├── wsgi.py
|  └── __init__.py
├── manage.py
├── templates
└── venv├── Lib├── pyvenv.cfg└── Scripts

創建模型

app/models.py

from django.db import models# Create your models here.
class PrettyNum(models.Model):mobile = models.CharField(verbose_name='手機號', max_length=11)# 想要循序為空 null = True blank =Treeprice = models.IntegerField(verbose_name='價格', default=0)level_choices = ((1, "1級"),(2, '2級'),(3, '3級'),)level = models.SmallIntegerField(verbose_name='級別', choices=level_choices, default=1)status_choices = ((1, "已占用"),(2, "未使用"))status = models.SmallIntegerField(verbose_name="狀態", choices=status_choices, default=2)

數據庫配置并注冊app

backend/settings.py

INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',#注冊app'app.apps.AppConfig'
]#這里使用mysql數據庫
DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql','NAME': 'tmpdb', #這里填寫數據名稱'USER': 'root','PASSWORD': '自定義數據庫密碼','HOST': 'mysql所在服務器IP','PORT':'mysql服務端口','OPTIONS':{"init_command":"SET sql_mode='STRICT_TRANS_TABLES'",}}
}

遷移數據模型

makemigrations
migrate

查看數據庫表

mysql> show tables;
+----------------------------+
| Tables_in_tmpdb            |
+----------------------------+
| app_prettynum              |
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
+----------------------------+

在數據庫模擬創建數據

mysql> SELECT * FROM app_prettynum ;
+----+------------+-------+-------+--------+
| id | mobile     | price | level | status |
+----+------------+-------+-------+--------+
|  1 | 123456     |    19 |     1 |      1 |
|  2 | 123457686  |    17 |     1 |      1 |
|  3 | 1234576888 |    10 |     1 |      1 |
|  4 | 1234576888 |    10 |     1 |      1 |
|  5 | 1234576888 |    10 |     1 |      1 |
|  6 | 1234576888 |    10 |     1 |      1 |
|  7 | 1234576888 |    10 |     1 |      1 |
+----+------------+-------+-------+--------+

靚號列表

  • url
  • 函數
    • 獲取所有靚號
    • 通過html+render將靚號羅列出

backend/urls.py

from django.contrib import admin
from django.urls import path
from app import viewsurlpatterns = [path('admin/', admin.site.urls),# 列表path('pretty/list/', views.pretty_list),
]

app/views.py

from django.shortcuts import renderfrom app.models import *# Create your views here.
def pretty_list(req):"""靚號列表"""# 選擇倒敘排序queryset = PrettyNum.objects.all().order_by("-price")return render(req, 'pretty_list.html', {"queryset": queryset})

在app下創建templates目錄

app/templates/pretty_list.html

<!DOCTYPE html>
<html>
<head><title>靚號列表</title><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css"><script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script><script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="panel panel-default"><!-- Default panel contents --><div class="panel-heading">Panel heading</div><div class="panel-body"></div><!-- Table --><table class="table"><thead><tr><th>ID</th><th>號碼</th><th>價格</th><th>級別</th><th>狀態</th><th>操作</th></tr></thead><tbody>{% for obj in queryset %}<tr><th>{{ obj.id }}</th><th>{{ obj.mobile }}</th><th>{{ obj.price }}</th><th>{{ obj.get_level_display }}</th><th>{{ obj.get_status_display }}</th></tr>{% endfor %}</tbody></table>
</div></body>
</html>

啟動服務,訪問

在這里插入圖片描述

準備提交添加

backend/urls.py

from django.contrib import admin
from django.urls import path
from app import viewsurlpatterns = [path('admin/', admin.site.urls),# 列表path('pretty/list/', views.pretty_list),# 添加path('pretty/add/', views.pretty_add),
]

app/views.py

from django.core.validators import RegexValidator
from django.shortcuts import render, redirect
from django import forms
from app.models import *# Create your views here.
def pretty_list(req):"""靚號列表"""# 選擇倒敘排序queryset = PrettyNum.objects.all().order_by("-price")return render(req, 'pretty_list.html', {"queryset": queryset})class PrettyModelForm(forms.ModelForm):class Meta:model = PrettyNumfields = ['mobile', 'price', 'level', 'status']def pretty_add(request):"""添加"""if request.method == "GET":form = PrettyModelForm()return render(request, 'pretty_add.html', {"form": form})form = PrettyModelForm(data=request.POST)if form.is_valid():form.save()return redirect('/pretty/list/')return render(request, 'pretty_add.html', {"form": form})

app/templates/pretty_add.html

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>添加</title><link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css"><script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script><script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body><div style="padding: 100px 100px 10px;"><form method="post" novalidate>{% csrf_token %}{% for filed in form %}<div><label>{{ filed.label }}</label>{{ filed }}</div>{% endfor %}<button type="submit" class="button">提交</button></form>
</div></body>
</html>

編輯靚號

  • 列表頁面:/pretty/數字/edit/
  • url
  • 函數
    • 根據ID獲取當前編輯對象
    • ModelForm配合,默認顯示數據
    • 提交修改

backend/urls.py

from django.contrib import admin
from django.urls import path
from app import viewsurlpatterns = [path('admin/', admin.site.urls),# 列表path('pretty/list/', views.pretty_list),# 添加path('pretty/add/', views.pretty_add),# 編輯path('pretty/<int:nid>/edit/', views.pretty_edit),
]

app/views.py

from django.core.validators import RegexValidator
from django.shortcuts import render, redirect
from django import forms
from app.models import *class PrettyEditModelForm(forms.ModelForm):mobile = forms.CharField(disabled=True, label="手機號")  # 不允許修改class Meta:model = PrettyNumfields = ['mobile', 'price', 'level', 'status']def pretty_edit(request, nid):row_obj = PrettyNum.objects.filter(id=nid).first()if request.method == "GET":form = PrettyEditModelForm(instance=row_obj)return render(request, 'pretty_edit.html', {"form": form})form = PrettyEditModelForm(data=request.POST, instance=row_obj)if form.is_valid():form.save()return redirect('/pretty/list/')return render(request, 'pretty_edit.html', {"form": form})

app/templates/pretty_edit.html

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>添加</title><link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css"><script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script><script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body><div style="padding: 100px 100px 10px;"><form method="post" novalidate>{% csrf_token %}{% for filed in form %}<div><label>{{ filed.label }}</label>{{ filed }}</div>{% endfor %}<button type="submit" class="button">提交</button></form>
</div></body>
</html>

查詢

根據電話號碼查詢

app/views.py

#Get方法
def pretty_list(request):"""靚號列表"""# 選擇倒敘排序data_dict = {}val = request.GET.get('q')queryset = queryset = PrettyNum.objects.all().filter(**data_dict).order_by("-price")if val:data_dict["mobile__contains"] = valqueryset = PrettyNum.objects.all().filter(**data_dict).order_by("-price")return render(request, 'pretty_list.html', {"queryset": queryset})

在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/38154.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/38154.shtml
英文地址,請注明出處:http://en.pswp.cn/news/38154.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

關于微信臨時文件wxfile://tmp文件如何處理,微信小程序最新獲取頭像和昵稱

分享-2023年資深前端進階&#xff1a;前端登頂之巔-最全面的前端知識點梳理總結&#xff0c;前端之巔 *分享一個使用比較久的&#x1fa9c; 技術棧&#xff1a;taro框架 vue3版本 解決在微信小程序獲取微信頭像時控制臺報錯&#xff1a;找不著wxfile://tmp 文件路徑,失敗&…

java spring cloud 企業電子招標采購系統源碼:營造全面規范安全的電子招投標環境,促進招投標市場健康可持續發展 tbms

? 項目說明 隨著公司的快速發展&#xff0c;企業人員和經營規模不斷壯大&#xff0c;公司對內部招采管理的提升提出了更高的要求。在企業里建立一個公平、公開、公正的采購環境&#xff0c;最大限度控制采購成本至關重要。符合國家電子招投標法律法規及相關規范&#xff0c;以…

支持M1 Syncovery for mac 文件備份同步工具

Syncovery for Mac 是一款功能強大、易于使用的文件備份和同步軟件&#xff0c;適用于需要備份和同步數據的個人用戶和企業用戶。Syncovery 提供了一個直觀的用戶界面&#xff0c;使用戶可以輕松設置備份和同步任務。用戶可以選擇備份的文件類型、備份目錄、備份頻率等&#xf…

解讀2023年上半年財報:營收凈利雙增長,珀萊雅離高端還有多遠?

夏季炎熱&#xff0c;防曬類產品的銷量暴漲。根據千牛數據&#xff0c;防曬衣今年5月全網搜索人數同比增長15%&#xff0c;加購人數同比增長29.8%&#xff0c;訪問人數同比增加42%。消費者狂熱的防曬需求&#xff0c;孕育著巨大的商機&#xff0c;許多企業開始瞄準這一機會。而…

在Windows和MacOS環境下實現批量doc轉docx,xls轉xlsx

一、引言 Python中批量進行辦公文檔轉化是常見的操作&#xff0c;在windows狀態下我們可以利用changeOffice這個模塊很快進行批量操作。 二、在Windows環境下的解決文案 Windows環境下&#xff0c;如何把doc轉化為docx&#xff0c;xls轉化為xlsx&#xff1f; 首先&#xff…

mysql三大日志—— 二進制日志binlog

binlog用于記錄數據庫執行的寫入性操作&#xff0c;由服務層進行記錄&#xff0c;通過追加的方式以二進制的形式保存在磁盤中。 binlog主要用于主從復制和數據恢復。 主從復制&#xff1a;在主機端開啟binlog&#xff0c;然后將binlog發送到各個從機&#xff0c;從機存放binl…

sykwalking8.2和mysql5.7快速部署

1.SkyWalking 是什么&#xff1f; 分布式系統的應用程序性能監視工具&#xff0c;專為微服務、云原生架構和基于容器&#xff08;Docker、K8s、Mesos&#xff09;架構而設計。 提供分布式追蹤、服務網格遙測分析、度量聚合和可視化一體化解決方案。 2.SkyWalking 有哪些功能…

Spring Task入門案例

Spring Task 是Spring框架提供的任務調度工具&#xff0c;可以按照約定的時間自動執行某個代碼邏輯。 定位&#xff1a;定時任務框架 作用&#xff1a;定時自動執行某段Java代碼 強調&#xff1a;只要是需要定時處理的場景都可以使用Spring Task 1. cron表達式 cron表達式…

Java多線程線程間的通信—wait及notify方法

線程間的相互作用 線程間的相互作用:線程之間需要一些協調通信,來共同完成一件任務。 Object類中相關的方法有兩個notify方法和三個wait方法: Object (Java Platform SE 7 ) 因為wait和notify方法定義在Object類中,因此會被所有的類所繼承。 這些方法都是final的,即它們…

樹形dp模板

285. 沒有上司的舞會 - AcWing題庫 #include<iostream> #include<cstdio> #include<cstdlib> #include<string> #include<cstring> #include<cmath> #include<ctime> #include<algorithm> #include<utility> #include&…

Visual Studio 與QT ui文件

對.ui文件鼠標右鍵&#xff0c;然后單擊 Open with…在彈出的窗口中&#xff0c;選中左側的 Qt Designer&#xff0c;然后單擊右側的 Add 按鈕&#xff0c;隨后會彈出一個窗口&#xff0c;在 Program: 輸入框中輸入 Qt Designer 的路徑&#xff0c;最后單擊 OK找到 Qt Designer…

內網ip與外網ip

一、關于IP地址 我們平時直接接觸最多的是內網IP。而且還可以自己手動修改ip地址。而外網ip&#xff0c;我們很少直接接觸&#xff0c;都是間接接觸、因為外網ip一般都是運營商管理&#xff0c;而且是全球唯一的&#xff0c;一般我們自己是無法修改的。 內網IP和外網IP是指在…

突破大模型 | Alluxio助力AI大模型訓練-成功案例(一)

更多詳細內容可見《Alluxio助力AI大模型訓練制勝寶典》 【案例一&#xff1a;知乎】多云緩存在知乎的探索:從UnionStore到Alluxio 作者&#xff1a;胡夢宇-知乎大數據基礎架構開發工程師&#xff08;內容轉載自InfoQ&#xff09; 一、背景 隨著云原生技術的飛速發展&#xff…

零基礎看懂免費開源的Stable Diffusion

文章目錄 前言Diffusion模型推理過程訓練過程 Stable Diffusion模型參考 前言 前面一篇文章主要講了擴散模型的理論基礎&#xff0c;還沒看過上篇的小伙伴可以點擊查看&#xff1a;DDPM理論基礎。這篇我們主要講一下一經推出&#xff0c;就火爆全網的Stable Diffusion模型。St…

django中使用ajax發送請求

1、ajax簡單介紹 瀏覽器向網站發送請求時 是以URL和表單的形式提交的post 或get 請求&#xff0c;特點是&#xff1a;頁面刷新 除此之外&#xff0c;也可以基于ajax向后臺發送請求&#xff08;異步&#xff09; 依賴jQuery 編寫ajax代碼 $.ajax({url: "發送的地址"…

filebeat多實例運行,kibana組件的基本使用

filebeat多實例運行: 1)需求 一臺服務器上&#xff0c;需要運行多個filebeat實例 2)啟動filebeat實例1 cat > config/11-log_tcp-to-console.yaml <<EOF filebeat.inputs: - type: log paths: - /tmp/oldboyedu-linux82/*.log # 監聽TCP的參數 - type:…

centos 安裝docker

1.更新你的系統: sudo yum update -y2.安裝必需的軟件包: Docker 需要 yum-utils, device-mapper-persistent-data 和 lvm2 軟件包來運行。安裝它們&#xff1a; sudo yum install -y yum-utils device-mapper-persistent-data lvm23.設置 Docker 的倉庫: 使用以下命令添加 D…

關于Redis,你需要學習了解的知識

關于 Redis &#xff0c;涵蓋多個方面&#xff0c;從基礎概念到高級應用&#xff0c;以及最佳實踐等。比如以下內容&#xff1a; 認識 Redis&#xff1a; Redis 是什么&#xff1f;它的特點和優勢是什么&#xff1f;Redis 的數據結構&#xff1a;字符串、哈希、列表、集合、有序…

Kafka的下載安裝以及使用

一、Kafka下載 下載地址&#xff1a;https://kafka.apache.org/downloads 二、Kafka安裝 因為選擇下載的是 .zip 文件&#xff0c;直接跳過安裝&#xff0c;一步到位。 選擇在任一磁盤創建空文件夾&#xff08;不要使用中文路徑&#xff09;&#xff0c;解壓之后把文件夾內容…

Redis 持久化

一、RDB 1.1 RDB持久化流程 fork子進程是阻塞的&#xff0c;如果同時開啟RDB和AOF&#xff0c;默認使用AOF。 1、Redis父進程首先判斷: 當前是否在執行save&#xff0c;或bgsave/bgrewriteaof (aof文件重寫命令)的子進程&#xff0c;如果在執行則bgsave命令直接返回。 2、父進…