Django 5 增删改查 小练习

1. 用命令创建目录和框架

django-admin startproject myapp

cd myapp

py manage.py startapp app

md templates

md static

md media

2. Ai 生成代码

一、app/models.py

from django.db import modelsclass Product(models.Model):name = models.CharField(max_length=255, verbose_name="商品名称")description = models.TextField( verbose_name="商品描述")quantity = models.PositiveIntegerField( verbose_name="商品数量")price = models.DecimalField(max_digits=10, decimal_places=2 , verbose_name="商品价格")class Meta:verbose_name = "商品"verbose_name_plural = verbose_namedef __str__(self):return self.nameclass Sale(models.Model):product = models.ForeignKey(Product, on_delete=models.CASCADE , verbose_name="商品")quantity_sold = models.PositiveIntegerField( verbose_name="销售数量")sale_date = models.DateTimeField(auto_now_add=True , verbose_name="销售日期")class Meta:verbose_name = "销售"verbose_name_plural = verbose_nameclass Purchase(models.Model):product = models.ForeignKey(Product, on_delete=models.CASCADE , verbose_name="商品")quantity_purchased = models.PositiveIntegerField( verbose_name="购买数量")purchase_date = models.DateTimeField(auto_now_add=True , verbose_name="购买日期")class Meta:verbose_name = "购买"verbose_name_plural = verbose_name

 二、myapp/settings.py

ALLOWED_HOSTS = ['*']INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','app',
]TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates','DIRS': [ BASE_DIR / 'templates'],'APP_DIRS': True,LANGUAGE_CODE = 'zh-hans'TIME_ZONE = 'Asia/Shanghai'STATIC_URL = 'static/'
# STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

 三、命令创建数据库

python manage.py makemigrations

python manage.py migrate

四、app/admin.py

from django.contrib import admin
from.models import Product, Sale, Purchaseadmin.site.register(Product)
admin.site.register(Sale)
admin.site.register(Purchase)

python manage.py createsuperuser # 创建后台用户 admin  test@qq.com  123456  y 

五、app/views.py

from django.shortcuts import render, redirect
from.models import Productdef product_list(request):products = Product.objects.all()total_quantity = sum(product.quantity for product in products)total_price = sum(product.price * product.quantity for product in products)return render(request, 'product_list.html', {'products': products, 'total_quantity': total_quantity, 'total_price': total_price})def add_product(request):if request.method == 'POST':name = request.POST['name']description = request.POST['description']quantity = int(request.POST['quantity'])price = float(request.POST['price'])product = Product(name=name, description=description, quantity=quantity, price=price)product.save()return redirect('product_list')return render(request, 'add_product.html')def update_product(request, product_id):product = Product.objects.get(pk=product_id)if request.method == 'POST':product.name = request.POST['name']product.description = request.POST['description']product.quantity = int(request.POST['quantity'])product.price = float(request.POST['price'])product.save()return redirect('product_list')return render(request, 'update_product.html', {'product': product})def delete_product(request, product_id):product = Product.objects.get(pk=product_id)if request.method == 'POST':product.delete()return redirect('product_list')return render(request, 'delete_product.html', {'product': product})

六、app/urls.py

from django.urls import path
from.views import product_list, add_product, update_product, delete_producturlpatterns = [path('products/', product_list, name='product_list'),path('products/add/', add_product, name='add_product'),path('products/update/<int:product_id>/', update_product, name='update_product'),path('products/delete/<int:product_id>/', delete_product, name='delete_product'),
]

七、myapp/urls.py

from django.contrib import admin
from django.urls import include, pathfrom app.views import product_list # 导入的视图函数 urlpatterns = [path('admin/', admin.site.urls),path('', product_list, name='home'), # 将根路径映射到 product_list 视图函数path('app/', include('app.urls')), # 将 app 应用中的 URL 映射到 app.urls 模块
]

八、myapp/templates 和 myapp/static

在 static 目录下载 layui (Layui - 极简模块化前端 UI 组件库(官方文档)) 解压到目录

在 templates 创建 product_list.html、add_product.html、delete_product.html、update_product.html

product_list.html

<!DOCTYPE html>
<html>{% load static %}
<head><title>Product List</title><link rel="stylesheet" type="text/css" href="{% static 'layui/css/layui.css' %}">
</head><body><div class="layui-container"><h1>Product List 商品列表</h1><table class="layui-table" lay-skin="line" lay-even><thead><tr><th>Name商品名称</th><th>Description 商品描述</th><th>Quantity 数量</th><th>Price 单价</th><th>Actions </th></tr></thead><tbody>{% for product in products %}<tr><td>{{ product.name }}</td><td>{{ product.description }}</td><td>{{ product.quantity }}</td><td>{{ product.price }}</td><td><a href="{% url 'update_product' product.id %}" class="layui-btn layui-btn-sm layui-btn-normal">Update 修改</a><a href="{% url 'delete_product' product.id %}" class="layui-btn layui-btn-sm layui-btn-danger">Delete 删除</a></td></tr>{% endfor %}</tbody></table><h2>Total Quantity 数量: {{ total_quantity }}</h2><h2>Total Price 总价: {{ total_price }}</h2><a href="{% url 'add_product' %}" class="layui-btn layui-btn-primary">Add Product 增加</a></div>
</body></html>

add_product.html

<!DOCTYPE html>
<html>
{% load static %}
<head><title>Add Product</title><link rel="stylesheet" type="text/css" href="{% static 'layui/css/layui.css' %}">
</head><body><div class="layui-container"><h1>Add Product</h1><form method="post">{% csrf_token %}<label for="name">Name:</label><input type="text" id="name" name="name" required class="layui-input"><br><label for="description">Description:</label><textarea id="description" name="description" class="layui-textarea"></textarea><br><label for="quantity">Quantity:</label><input type="number" id="quantity" name="quantity" required class="layui-input"><br><label for="price">Price:</label><input type="number" step="0.01" id="price" name="price" required class="layui-input"><br><input type="submit" value="Add Product" class="layui-btn"></form>
</div>
</body></html>

delete_product.html

<!DOCTYPE html>
<html>{% load static %}
<head><title>Delete Product</title><link rel="stylesheet" type="text/css" href="{% static 'layui/css/layui.css' %}">
</head><body><div class="layui-container"><h1>Confirm Deletion </h1><p>Are you sure you want to delete 是否要删除 "{{ product.name }}"?</p><form method="post" class="layui-form" >{% csrf_token %}<input type="submit" value="Yes, Delete 删除" class="layui-btn layui-btn-danger"><a href="{% url 'product_list' %}" class="layui-btn layui-btn-primary">Cancel 取消</a></form>
</div>
</body></html>

update_product.html

<!DOCTYPE html>
<html>{% load static %}
<head><title>Update Product</title><link rel="stylesheet" type="text/css" href="{% static 'layui/css/layui.css' %}">
</head><body><div class="layui-container"><h1>Update Product</h1><form method="post">{% csrf_token %}<label for="name">Name:</label><input type="text" id="name" name="name" value="{{ product.name }}" required class="layui-input"><br><label for="description">Description:</label><textarea id="description" name="description" class="layui-textarea" required>{{ product.description }}</textarea><br><label for="quantity">Quantity:</label><input type="number" id="quantity" name="quantity" value="{{ product.quantity }}" required class="layui-input"><br><label for="price">Price:</label><input type="number" step="0.01" id="price" name="price" value="{{ product.price }}" required class="layui-input"><br><input type="submit" value="Update Product" class="layui-btn"></form></div>
</body></html>

八、 运行

python manage.py runserver 

 3. 用TKinter 查看数据表 与出数据

pip install openpyxl

pip install reportlab

myapp/viewSQL.py 

import sqlite3
import tkinter as tk
from tkinter import ttk
import openpyxl
from tkinter import messagebox
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import osdef get_table_names():conn = sqlite3.connect('db.sqlite3')cursor = conn.cursor()cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")table_names = [row[0] for row in cursor.fetchall()]conn.close()return table_namesdef fetch_data(table_name):conn = sqlite3.connect('db.sqlite3')cursor = conn.cursor()cursor.execute(f'SELECT * FROM {table_name}')data = cursor.fetchall()conn.close()return datadef display_table_names():names = get_table_names()for item in tree.get_children():tree.delete(item)for name in names:tree.insert('', 'end', values=(name,))def display_data_for_selected_table(event):selected_item = tree.focus()if selected_item:table_name = tree.item(selected_item)['values'][0]data = fetch_data(table_name)for item in data_tree.get_children():data_tree.delete(item)for row in data:data_tree.insert('', 'end', values=row)def export_to_excel():selected_item = tree.focus()if selected_item:table_name = tree.item(selected_item)['values'][0]data = fetch_data(table_name)wb = openpyxl.Workbook()ws = wb.activews.append([f'Column {i + 1}' for i in range(len(data[0]))])for row in data:ws.append(row)filename = f'{table_name}.xlsx'wb.save(filename)messagebox.showinfo("Export Success", f"Data exported to {filename}")def print_to_pdf():selected_item = tree.focus()if selected_item:table_name = tree.item(selected_item)['values'][0]data = fetch_data(table_name)pdf_filename = f'{table_name}_pdf_export.pdf'c = canvas.Canvas(pdf_filename, pagesize=letter)y = 750c.setFont("Helvetica", 12)c.drawString(50, y, f"Table Name: {table_name}")y -= 20for row in data:row_str = ", ".join(str(item) for item in row)c.drawString(50, y, row_str)y -= 15c.save()messagebox.showinfo("PDF Export Success", f"Data printed to {pdf_filename}")def print_to_markdown():selected_item = tree.focus()if selected_item:table_name = tree.item(selected_item)['values'][0]data = fetch_data(table_name)markdown_filename = f'{table_name}_markdown_export.md'with open(markdown_filename, 'w') as f:f.write(f'# {table_name}\n')for row in data:row_str = " | ".join(str(item) for item in row)f.write(f'| {row_str} |\n')messagebox.showinfo("Markdown Export Success", f"Data printed to {markdown_filename}")root = tk.Tk()
root.title("SQLite3 Table Viewer and Exporter 查看器与导出器")# Treeview for table names
tree = ttk.Treeview(root, columns=("Table Name",), show="headings")
tree.heading("Table Name", text="Table Name")
tree.column("Table Name", width=400)
tree.pack(padx=10, pady=10)# Treeview for table data
data_tree = ttk.Treeview(root, columns=("column1", "column2", "column3", "column4", "column5", "..."), show="headings")
for col in ("column1", "column2", "column3", "column4", "column5", "..."):data_tree.heading(col, text=col)data_tree.column(col, width=100)
data_tree.pack(padx=10, pady=10)button_fetch = tk.Button(root, text="Fetch Table Names 查看表名", command=display_table_names)
button_fetch.pack(pady=10)export_button = tk.Button(root, text="Export to Excel 导出为Excel", command=export_to_excel)
export_button.pack(pady=10)print_pdf_button = tk.Button(root, text="Print to PDF 打印为PDF", command=print_to_pdf)
print_pdf_button.pack(pady=10)print_markdown_button = tk.Button(root, text="Print to Markdown 打印为Markdown", command=print_to_markdown)
print_markdown_button.pack(pady=10)tree.bind("<Double-1>", display_data_for_selected_table)root.mainloop()

4. 一键生成 代码 

/app.py

import subprocess
import osdef replace_content_in_file(file_path, keyword, new_content):try:with open(file_path, 'r', encoding='utf-8') as file:lines = file.readlines()with open(file_path, 'w', encoding='utf-8') as file:for line in lines:if keyword in line:line = line.replace(keyword, new_content)file.write(line)print(f"成功在文件中找到'{keyword}'并进行了替换。")except FileNotFoundError:print(f"文件 {file_path} 不存在。")# 使用示例
# file_path = 'myapp/settings.py'
# keyword = 'ALLOWED_HOSTS = []'
# new_content = "ALLOWED_HOSTS = ['*']"
# replace_content_in_file(file_path, keyword, new_content)def add_content_after_keyword(file_path, keyword, new_content):try:with open(file_path, 'r', encoding='utf-8') as file:lines = file.readlines()with open(file_path, 'w', encoding='utf-8') as file:for line in lines:if keyword in line:line = line.rstrip() + new_content + '\n'file.write(line)print(f"成功在文件中找到'{keyword}'并添加了内容。")except FileNotFoundError:print(f"文件 {file_path} 不存在。")# 使用示例
# file_path = 'myapp/settings.py'
# keyword = "'django.contrib.staticfiles',"
# new_content = "\n\t'app',"def create_django_project_and_app(project_name, app_name):try:# 创建 Django 项目subprocess.run(["django-admin", "startproject", project_name], check=True)# 切换到项目目录os.chdir(project_name)# 创建应用subprocess.run(["python", "manage.py", "startapp", app_name], check=True)# 创建templates目录os.makedirs('templates', exist_ok=True)# 创建 static 目录os.makedirs('static', exist_ok=True)# 创建media目录os.makedirs('media', exist_ok=True)file_path = project_name +'/settings.py'keyword = "'django.contrib.staticfiles',"new_content = "\n\t"+"'"+app_name+"'"+","add_content_after_keyword(file_path, keyword, new_content)file_path = project_name +'/settings.py'keyword = 'ALLOWED_HOSTS = []'new_content = "ALLOWED_HOSTS = ['*']"replace_content_in_file(file_path, keyword, new_content)file_path = project_name +'/settings.py'keyword = "'DIRS': [],"new_content = "'DIRS': [ BASE_DIR / 'templates'],"replace_content_in_file(file_path, keyword, new_content)file_path = project_name +'/settings.py'keyword = "LANGUAGE_CODE = 'en-us'"new_content = "LANGUAGE_CODE = 'zh-hans'"replace_content_in_file(file_path, keyword, new_content)file_path = project_name +'/settings.py'keyword = "TIME_ZONE = 'UTC'"new_content = "TIME_ZONE = 'Asia/Shanghai'"replace_content_in_file(file_path, keyword, new_content)file_path = project_name +'/settings.py'keyword = "from pathlib import Path"new_content = "from pathlib import Path\nimport os"replace_content_in_file(file_path, keyword, new_content)file_path = project_name +'/settings.py'keyword = "STATIC_URL = 'static/'"new_content = "STATIC_URL = 'static/'\nSTATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')"replace_content_in_file(file_path, keyword, new_content)# 执行 makemigrations 命令subprocess.run(["python", "manage.py", "makemigrations"], check=True)# 执行 migrate 命令subprocess.run(["python", "manage.py", "migrate"], check=True)# 创建超级用户os.system("python manage.py createsuperuser")# 运行开发服务器subprocess.run(["python", "manage.py", "runserver"], check=True)print(f"成功创建 Django 项目:{project_name},并创建应用:{app_name}")except subprocess.CalledProcessError as e:print(f"创建过程中出现错误:{e}")# 使用示例
# project_name = "myapp"
# app_name = "app"
project_name = input("请输入 Django 项目名称:")
app_name = input("请输入应用名称:")
create_django_project_and_app(project_name, app_name)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/460711.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

苏州金龙技术创新赋能旅游新质生产力

2024年10月23日&#xff0c;备受瞩目的“2024第六届旅游出行大会”在云南省丽江市正式开幕。作为客车行业新质生产力标杆客车&#xff0c;苏州金龙在大会期间现场展示了新V系V12商旅版、V11和V8E纯电车型&#xff0c;为旅游出行提供全新升级方案。 其中&#xff0c;全新15座V1…

Atlas800昇腾服务器(型号:3000)—SwinTransformer等NPU推理【图像分类】(九)

服务器配置如下&#xff1a; CPU/NPU&#xff1a;鲲鹏 CPU&#xff08;ARM64&#xff09;A300I pro推理卡 系统&#xff1a;Kylin V10 SP1【下载链接】【安装链接】 驱动与固件版本版本&#xff1a; Ascend-hdk-310p-npu-driver_23.0.1_linux-aarch64.run【下载链接】 Ascend-…

14. NSWindow 窗口与 NSWindowController 窗口控制器

NSWindowController窗口控制器主要用于管理xib/storyboard文件中加载的NSWindow对象&#xff1a;1、创建一个基于xib或storyboard的NSWindowController子类会自动创建一个NSWindow&#xff1b;2、如果手工创建NSWindow对象&#xff0c;则需要维护NSWindowController和NSWindow之…

02 什么是Babel

什么是Babel&#xff1f; Babel 是一个 JavaScript 编译器,提供了JavaScript的编译过程&#xff0c;能够将源代码转换为目标代码。AST -> Transform -> Generate 官网 Babel Babel 查看AST https://astexplorer.net/ Babel所有的包 babel/traverse Babel Babel 是…

【论文阅读笔记】VLP: A Survey on Vision-language Pre-training

目录 前言2 特征提取&#xff08;Feature extraction&#xff09;2.1.1 图象特征提取OD-based Region feature / RoIFreeze the pre-trained object detectorsGrid features&#xff08;网格特征&#xff09;CNN-GFsEnd-to-End Training&#xff08;端到端训练&#xff09;ViT-…

TortoiseSVN小乌龟下载安装(Windows11)

目录 TortoiseSVN 1.14.7工具下载安装 TortoiseSVN 1.14.7 工具 系统&#xff1a;Windows 11 下载 官网&#xff1a;https://tortoisesvn.subversion.org.cn/downloads.html如图选 TortoiseSVN 1.14.7 - 64 位 下载完成 安装 打开 next&#xff0c;next Browse&#xf…

Mac OS 搭建MySQL开发环境

Mac OS 搭建MySQL开发环境 文章目录 Mac OS 搭建MySQL开发环境一、安装Mysql&#xff1a;二、配置环境变量三、安装Navicat 本地环境&#xff1a; Mac OS Sequoia15.0.1&#xff08;M3 Max) 目标状态&#xff1a; 下载安装Mysql&#xff0c;配置相关环境。 一、安装Mysql&…

docker Desktop开启远程访问端口

文章目录 问题解决方法1.首先开启docker Desktop的访问端口2.将本地端口绑定远程访问ip 验证 问题 Windows上部署的docker&#xff0c;没办法通过远程的ip进行访问&#xff0c;实现远程代码的部署。 解决方法 1.首先开启docker Desktop的访问端口 通过开启docker访问端口&am…

Linux文件系统学习(未完)

1. Linux文件系统的特点与类别 1.1 特点 Linux系统中&#xff0c;文件组织在一个统一的树形目录结构中&#xff0c;整个文件系统有一个根“/”&#xff08;文件夹&#xff09;&#xff0c;然后以每个目录&#xff08;文件夹&#xff09;作为分叉&#xff0c;叶子节点作为文件…

Three.js 快速入门构建你的第一个 3D 应用

![ 开发领域&#xff1a;前端开发 | AI 应用 | Web3D | 元宇宙 技术栈&#xff1a;JavaScript、React、Three.js、WebGL、Go 经验经验&#xff1a;6年 前端开发经验&#xff0c;专注于图形渲染和AI技术 开源项目&#xff1a;github 晓智元宇宙、数字孪生引擎、前端面试题 大家好…

排序算法汇总

一、二分查找 public static int binarySearch(int[] nums,int target){int l 0, r nums.length-1;while(l < r){int mid l (r-l)/2;if(nums[mid] target){return mid;}else if(nums[mid] < target){r mid - 1;}else{l mid 1;}}return -1;} 对于防止溢出的 mid …

类和对象(2)

1.类的默认成员函数 默认成员函数就是⽤⼾没有显式实现&#xff0c;编译器会⾃动⽣成的成员函数称为默认成员函数。⼀个类&#xff0c;我们不写的情况下编译器会默认⽣成以下6个默认成员函数&#xff0c;需要注意的是这6个中最重要的是前4个&#xff0c;最后两个取地址重载不…

AcWing 1303:斐波那契前 n 项和 ← 矩阵快速幂加速递推

【题目来源】https://www.acwing.com/problem/content/1305/http://poj.org/problem?id3070【题目描述】 大家都知道 数列吧&#xff0c;。现在问题很简单&#xff0c;输入 和 &#xff0c;求 的前 项和 。【输入格式】 共一行&#xff0c;包含两个整数 和 。【输出格式】…

ElasticSearch备考 -- Index rollover

一、题目 给索引my-index-000001&#xff0c;创建别名my-index&#xff0c;并设置rollover&#xff0c;满足以下三个条件的 The index was created 7 or more days ago.The index contains 5 or more documents.The index’s largest primary shard is 1GB or larger. 二、思考…

zabbix 6.0 监控clickhouse(单机)

zabbix 6.0 LTS已经包含了clickhouse的监控模板&#xff0c;所以我们可以直接使用自带的模板来监控clickhouse了。 0.前置条件 clickhouse 已经安装&#xff0c;我安装的是24.3.5.47zabbix-agent 已经安装并配置。系统是ubuntu 2204 server 1. 新建监控用户 使用xml的方式为…

Jmeter自动化实战

一、前言 由于系统业务流程很复杂,在不同的阶段需要不同的数据,且数据无法重复使用,每次造新的数据特别繁琐,故想着能不能使用jmeter一键造数据 二、创建录制模板 可参考:jmeter录制接口 首先创建一个录制模板 因为会有各种请求头,cookies,签名,认证信息等原因,导致手动复制…

提升网站速度与性能优化的有效策略与实践

内容概要 在数字化快速发展的今天&#xff0c;网站速度与性能优化显得尤为重要&#xff0c;它直接影响用户的浏览体验。用户在访问网站时&#xff0c;往往希望能够迅速获取信息&#xff0c;若加载时间过长&#xff0c;轻易可能导致他们转向其他更为流畅的网站。因此&#xff0…

OpenCV视觉分析之目标跟踪(6)轻量级目标跟踪器类TrackerNano的使用

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 Nano 跟踪器是一个超轻量级的基于深度神经网络&#xff08;DNN&#xff09;的通用目标跟踪器。 由于特殊的模型结构&#xff0c;Nano 跟踪器速度…

C数组手动输入问题

问题界面 解析 输入数组数据也需要加取地址符吗&#xff1f;数组不就是地址了吗&#xff1f; 理解array[i]和array[i][j]的区别&#xff1a; array[i]是一个指向第i行第一个元素的指针&#xff08;int*类型&#xff0c;指向array[i][0]&#xff09;。 array[i][j]是一个int类…

Hadoop-002-部署并配置HDFS集群

集群规划 Hadoop HDFS的角色包含 NameNode(主节点管理者)、DataNode(从节点工作者)、SeconddaryNameNode(从节点辅助) 节点CPU内存hadoop-11C4Ghadoop-21C2Ghadoop-31C2G 一、下载上传Hadoop包 注意: 登录hadoop-1节点root用户执行 1、官网下载安装包后上传 到hadoop-1服务…