Compare commits

...

13 Commits

Author SHA1 Message Date
48bb1b3c12 新增“数据编辑” 2025-10-14 19:14:43 +08:00
8a752b2b92 新增“数据编辑” 2025-10-14 18:00:40 +08:00
a678adf646 新增“数据编辑” 2025-10-14 16:00:45 +08:00
08994d732d Merge remote-tracking branch 'origin/main-v2'
# Conflicts:
#	ESConnect.py
#	app.py
2025-10-14 15:46:11 +08:00
9c011dfc8c 新增“数据编辑” 2025-10-14 15:37:22 +08:00
aa6b1dec3f 新增“数据编辑” 2025-10-14 15:35:32 +08:00
0926ab2535 处理冲突 2025-10-14 15:17:51 +08:00
81f1eae2d5 新增“数据编辑” 2025-10-14 15:01:14 +08:00
e887494796 2025-10-14 14:51:08 +08:00
263b396142 新增“数据编辑” 2025-10-14 14:26:36 +08:00
068e675fd1 Merge remote-tracking branch 'origin/main' into main-v2
# Conflicts:
#	app.py
2025-10-14 13:54:15 +08:00
5a6f799059 新增“数据编辑” 2025-10-06 22:04:48 +08:00
8c530ff599 新增“数据编辑” 2025-10-02 15:49:36 +08:00
21 changed files with 733 additions and 264 deletions

8
.idea/.gitignore generated vendored
View File

@@ -1,8 +0,0 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@@ -1,23 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="Flask">
<option name="enabled" value="true" />
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Achievement_Inputing" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="GOOGLE" />
<option name="myDocStringFormat" value="Google" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Jinja2" />
<option name="TEMPLATE_FOLDERS">
<list>
<option value="$MODULE_DIR$/templates" />
</list>
</option>
</component>
</module>

View File

@@ -1,6 +0,0 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

7
.idea/misc.xml generated
View File

@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Achievement_Inputing" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Achievement_Inputing" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml generated
View File

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/Achievement_Inputing.iml" filepath="$PROJECT_DIR$/.idea/Achievement_Inputing.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated
View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

View File

@@ -3,6 +3,7 @@ from elasticsearch import Elasticsearch
# import json
import hashlib
import requests
import json
# Elasticsearch连接配置
ES_URL = "http://localhost:9200"
@@ -24,6 +25,7 @@ def create_index_with_mapping():
"mappings": {
"properties": {
"writer_id":{"type": "text"},
"data": {
"type": "text", # 存储转换后的字符串,支持分词搜索
"analyzer": "ik_max_word",
@@ -60,6 +62,9 @@ def create_index_with_mapping():
write_user_data(admin)
else:
print(f"索引 {users_index_name} 已存在")
def update_document(es, index_name, doc_id=None, updated_doc=None):
"""更新指定ID的文档"""
es.update(index=index_name, id=doc_id, body={"doc": updated_doc})
def get_doc_id(data):
@@ -142,6 +147,49 @@ def delete_by_id(doc_id):
print("删除失败:", str(e))
return False
def update_by_id(doc_id, updated_data):
"""
根据文档ID更新数据
参数:
doc_id (str): 要更新的文档ID
updated_data (dict): 更新的数据内容
返回:
bool: 更新成功返回True失败返回False
"""
try:
# 执行更新操作
es.update(index=data_index_name, id=doc_id, body={"doc": updated_data})
print(f"文档 {doc_id} 更新成功")
return True
except Exception as e:
print(f"更新失败: {str(e)}")
return False
def get_by_id(doc_id):
"""
根据文档ID获取单个文档
参数:
doc_id (str): 要获取的文档ID
返回:
dict or None: 成功返回文档数据失败返回None
"""
try:
# 执行获取操作
result = es.get(index=data_index_name, id=doc_id)
if result['found']:
return {
"_id": result['_id'],
**result['_source']
}
return None
except Exception as e:
print(f"获取文档失败: {str(e)}")
return None
def search_by_any_field(keyword):
"""全字段模糊搜索(支持拼写错误)"""
try:

76
app.py
View File

@@ -7,18 +7,19 @@ from PIL import Image
import re
import json
import requests
from functools import wraps
from ESConnect import *
from json_converter import json_to_string, string_to_json
from openai import OpenAI
from functools import wraps
# import config
# 创建Flask应用实例
app = Flask(__name__)
# 设置会话密钥,用于加密会话数据
app.secret_key = 'your-secret-key-change-this-in-production'
# app.config.from_object(config.Config)
# 设置会话密钥,用于加密会话数据
app.secret_key = 'your-secret-key-change-this-in-production'
# OCR和信息提取函数使用大模型API处理图片并提取结构化信息
# 权限装饰器
def login_required(f):
"""要求用户登录的装饰器"""
@@ -29,7 +30,6 @@ def login_required(f):
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
def admin_required(f):
"""要求管理员权限的装饰器"""
@wraps(f)
@@ -42,7 +42,6 @@ def admin_required(f):
return redirect(url_for('index'))
return f(*args, **kwargs)
return decorated_function
def user_or_admin_required(f):
"""要求普通用户或管理员权限的装饰器"""
@wraps(f)
@@ -57,7 +56,6 @@ def user_or_admin_required(f):
return f(*args, **kwargs)
return decorated_function
# OCR和信息提取函数使用大模型API处理图片并提取结构化信息
def ocr_and_extract_info(image_path):
"""
使用大模型API进行OCR识别并提取图片中的结构化信息
@@ -213,6 +211,7 @@ def login():
return render_template('login.html')
# 登出路由
@app.route('/logout')
def logout():
@@ -223,6 +222,7 @@ def logout():
flash('已成功登出', 'info')
return redirect(url_for('login'))
# 用户管理页面路由
@app.route('/user_management')
@admin_required
@@ -233,6 +233,7 @@ def user_management():
users = get_all_users()
return render_template('user_management.html', users=users)
# 注册新用户路由
@app.route('/register', methods=['GET', 'POST'])
@admin_required
@@ -279,6 +280,7 @@ def register():
return render_template('register.html')
# 修改用户密码路由
@app.route('/change_password/<username>', methods=['POST'])
@admin_required
@@ -309,6 +311,7 @@ def change_password(username):
return redirect(url_for('user_management'))
# 修改用户权限路由
@app.route('/change_permission/<username>', methods=['POST'])
@admin_required
@@ -326,6 +329,7 @@ def change_permission(username):
return redirect(url_for('user_management'))
# 删除用户路由
@app.route('/delete_user/<username>', methods=['POST'])
@admin_required
@@ -341,6 +345,7 @@ def delete_user_route(username):
return redirect(url_for('user_management'))
# 个人设置页面路由
@app.route('/profile')
@login_required
@@ -350,6 +355,7 @@ def profile():
"""
return render_template('profile.html')
# 修改个人密码路由
@app.route('/change_own_password', methods=['POST'])
@login_required
@@ -383,6 +389,7 @@ def change_own_password():
return redirect(url_for('profile'))
# 个人数据页面路由
@app.route('/my_data')
@login_required
@@ -474,10 +481,7 @@ def upload_image():
# 确认录入路由
@app.route('/confirm', methods=['POST'])
<<<<<<< HEAD
@user_or_admin_required
=======
>>>>>>> 30645e46ff2a6ee5c12fd95fb21b7eb4fb51c5f0
def confirm_data():
"""
确认并录入用户编辑后的数据
@@ -502,18 +506,11 @@ def confirm_data():
data_string = json_to_string(edited_data)
print(f"转换后的数据字符串: {data_string}")
<<<<<<< HEAD
# 构造新的数据结构只包含data和image字段并添加用户ID
processed_data = {
"data": data_string,
"image": image_filename, # 存储图片文件名
"user_id": session['user_id'] # 添加用户ID关联
=======
# 构造新的数据结构只包含data和image字段
processed_data = {
"data": data_string,
"image": image_filename # 存储图片文件名
>>>>>>> 30645e46ff2a6ee5c12fd95fb21b7eb4fb51c5f0
}
print(f"准备存储的数据: {processed_data}")
@@ -632,13 +629,13 @@ def serve_image(filename):
@login_required
def delete_entry(doc_id):
"""
根据文档ID删除数据(用户只能删除自己的数据,管理员可以删除所有数据)
根据文档ID删除数据
参数:
doc_id (str): 要删除的文档ID
返回:
重定向到相应页面或错误信息
重定向到所有数据页面或错误信息
"""
user_id = session['user_id']
user_permission = session.get('permission', 1)
@@ -653,10 +650,49 @@ def delete_entry(doc_id):
if success:
return redirect(url_for(redirect_url))
if delete_by_id(doc_id):
return redirect(url_for('show_all'))
else:
return "删除失败", 500
# 编辑数据路由
# 批量删除数据路由
@app.route('/batch_delete', methods=['POST'])
@admin_required
def batch_delete():
"""
批量删除选中的数据(仅管理员可访问)
返回:
重定向到所有数据页面或错误信息
"""
try:
# 获取选中的文档ID列表
doc_ids = request.form.getlist('doc_ids')
if not doc_ids:
flash('请选择要删除的记录', 'error')
return redirect(url_for('show_all'))
# 批量删除选中的文档
success_count = 0
for doc_id in doc_ids:
if delete_by_id(doc_id):
success_count += 1
if success_count > 0:
flash(f'成功删除 {success_count} 条记录', 'success')
else:
flash('删除失败,请重试', 'error')
return redirect(url_for('show_all'))
except Exception as e:
print(f"批量删除失败: {str(e)}")
flash('批量删除失败,请重试', 'error')
return redirect(url_for('show_all'))
@app.route('/edit/<doc_id>', methods=['GET', 'POST'])
@login_required
def edit_entry(doc_id):
@@ -740,8 +776,6 @@ def edit_entry(doc_id):
flash('保存数据失败', 'error')
return redirect(url_for('my_data'))
# 主程序入口
if __name__ == '__main__':
# 创建Elasticsearch索引

Binary file not shown.

Before

Width:  |  Height:  |  Size: 414 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 414 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 414 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 414 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 414 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 414 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 414 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 414 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 414 KiB

View File

@@ -27,50 +27,87 @@
margin-bottom: 15px;
}
/* 表格容器 - 顶部边距调整 */
.table-container {
overflow-x: auto;
margin-top: 15px; /* 减少顶部间距 */
/* 卡片容器样式 */
.data-cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
gap: 20px;
margin-bottom: 20px;
}
/* 卡片样式 */
.data-card {
background-color: white;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
padding: 20px;
border: 1px solid #e0e0e0;
transition: transform 0.3s, box-shadow 0.3s;
}
/* 表格样式 */
table {
width: 100%;
border-collapse: collapse;
font-family: 'Segoe UI', Arial, sans-serif;
.data-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
/* 表头样式 */
thead {
background: linear-gradient(135deg, #3498db, #1a5276);
color: white;
/* 卡片头部样式 */
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
padding-bottom: 15px;
border-bottom: 1px solid #f0f0f0;
}
th {
padding: 16px 12px;
text-align: left;
.card-header h3 {
margin: 0;
color: #333;
font-size: 18px;
}
.card-actions {
display: flex;
gap: 8px;
}
/* 卡片内容样式 */
.card-content {
margin-bottom: 15px;
}
.field-item {
display: flex;
margin-bottom: 10px;
line-height: 1.5;
}
.field-key {
font-weight: 600;
color: #333;
min-width: 120px;
margin-right: 10px;
}
/* 表格行样式 */
tbody tr {
border-bottom: 1px solid #eef1f5;
transition: background-color 0.3s;
.field-value {
color: #666;
flex: 1;
word-break: break-word;
}
tbody tr:nth-child(even) {
background-color: #f8fafc;
/* 卡片图片样式 */
.card-image {
text-align: center;
margin-top: 15px;
padding-top: 15px;
border-top: 1px solid #f0f0f0;
}
tbody tr:hover {
background-color: #e3f2fd;
}
td {
padding: 14px 12px;
color: #4a5568;
.card-image img {
max-width: 100%;
max-height: 200px;
border-radius: 4px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
/* 操作按钮样式 */
@@ -81,6 +118,17 @@
cursor: pointer;
font-weight: 500;
transition: all 0.3s;
margin: 0 2px;
}
.edit-btn {
background: linear-gradient(to right, #4CAF50, #45a049);
color: white;
}
.edit-btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(76, 175, 80, 0.3);
}
.delete-btn {
@@ -117,48 +165,189 @@
padding: 40px 0;
color: #a0aec0;
font-style: italic;
grid-column: 1 / -1;
}
/* 响应式设计 */
@media (max-width: 768px) {
.data-cards {
grid-template-columns: 1fr;
}
.card-header {
flex-direction: column;
align-items: flex-start;
gap: 10px;
}
.card-actions {
align-self: flex-end;
}
.field-item {
flex-direction: column;
}
.field-key {
min-width: auto;
margin-bottom: 5px;
}
}
</style>
<div class="container">
<h2>所有已录入的奖项信息</h2>
<p>在此页面可以查看所有已录入的成果信息,并进行删除操作</p>
<p>在此页面可以查看所有已录入的成果信息,并进行编辑和删除操作</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>比赛/论文名称</th>
<th>项目名称</th>
<th>学生</th>
<th>指导老师</th>
<th style="text-align: center;">操作</th>
</tr>
</thead>
<tbody>
<!-- 批量操作区域 -->
<div class="batch-operations" style="margin-bottom: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 8px; border: 1px solid #e0e0e0;">
<div style="display: flex; align-items: center; gap: 15px;">
<div style="display: flex; align-items: center; gap: 8px;">
<input type="checkbox" id="select-all" onchange="toggleSelectAll(this.checked)">
<label for="select-all" style="font-weight: 600; color: #333;">全选</label>
</div>
<button type="button" class="batch-delete-btn" onclick="batchDelete()" style="padding: 8px 16px; background-color: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer; font-weight: 500; transition: background-color 0.3s;">
批量删除选中项
</button>
<span id="selected-count" style="color: #666; font-size: 14px;">已选择 0 项</span>
</div>
</div>
<div class="data-cards">
{% if data %}
{% for item in data %}
<tr>
<td>{{ item.id or '无' }}</td>
<td>{{ item.name or '无' }}</td>
<td>{% if item.students is string %}{{ item.students or '无' }}{% else %}{{ item.students|join(', ') if item.students else '无' }}{% endif %}</td>
<td>{% if item.teacher is string %}{{ item.teacher or '无' }}{% else %}{{ item.teacher|join(', ') if item.teacher else '无' }}{% endif %}</td>
<td style="text-align: center;">
<form action="{{ url_for('delete_entry', doc_id=item._id) }}" method="POST" onsubmit="return confirm('确定要删除这条记录吗?')">
<button type="submit" class="action-button delete-btn">删除</button>
</form>
</td>
</tr>
<div class="data-card">
<div class="card-header">
<div style="display: flex; align-items: center; gap: 15px;">
<input type="checkbox" class="doc-checkbox" value="{{ item._id }}" onchange="updateSelectedCount()">
<h3>记录 {{ loop.index }}</h3>
</div>
<div class="card-actions">
<a href="{{ url_for('edit_entry', doc_id=item._id) }}" class="action-button edit-btn">编辑</a>
</div>
</div>
<div class="card-content">
{% if item.data %}
{# 从原始数据中解析字段 #}
{% set data_string = item.data %}
{% set pairs = data_string.split('|###|') %}
{% for pair in pairs %}
{% if ':' in pair %}
{% set key_value = pair.split(':', 1) %}
{% set field_key = key_value[0].strip() %}
{% set field_value = key_value[1].strip() %}
{# 处理列表格式 [item1|##|item2] #}
{% if field_value.startswith('[') and field_value.endswith(']') %}
{% set list_content = field_value[1:-1] %}
{% set field_value = list_content.split('|##|')|join(', ') %}
{% endif %}
<div class="field-item">
<span class="field-key">{{ field_key }}</span>
<span class="field-value">{{ field_value or '无' }}</span>
</div>
{% endif %}
{% endfor %}
{% else %}
<tr>
<td colspan="5" class="no-data">暂无数据</td>
</tr>
{# 如果没有data字段显示解析后的字段 #}
{% for key, value in item.items() %}
{% if key not in ['_id', 'image'] %}
<div class="field-item">
<span class="field-key">{{ key }}</span>
<span class="field-value">
{% if value is sequence and value is not string %}
{{ value|join(', ') if value else '无' }}
{% else %}
{{ value or '无' }}
{% endif %}
</span>
</div>
{% endif %}
{% endfor %}
{% endif %}
</div>
</div>
{% endfor %}
{% else %}
<div class="no-data">暂无数据</div>
{% endif %}
</tbody>
</table>
</div>
<a href="{{ url_for('index') }}" class="back-btn">返回首页</a>
</div>
<script>
// 全选/取消全选功能
function toggleSelectAll(checked) {
const checkboxes = document.querySelectorAll('.doc-checkbox');
checkboxes.forEach(checkbox => {
checkbox.checked = checked;
});
updateSelectedCount();
}
// 更新选择计数
function updateSelectedCount() {
const checkboxes = document.querySelectorAll('.doc-checkbox');
const selectedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
document.getElementById('selected-count').textContent = `已选择 ${selectedCount}`;
// 更新全选复选框状态
const selectAllCheckbox = document.getElementById('select-all');
if (selectedCount === 0) {
selectAllCheckbox.checked = false;
selectAllCheckbox.indeterminate = false;
} else if (selectedCount === checkboxes.length) {
selectAllCheckbox.checked = true;
selectAllCheckbox.indeterminate = false;
} else {
selectAllCheckbox.checked = false;
selectAllCheckbox.indeterminate = true;
}
}
// 批量删除功能
function batchDelete() {
const checkboxes = document.querySelectorAll('.doc-checkbox:checked');
if (checkboxes.length === 0) {
alert('请至少选择一条记录进行删除');
return;
}
const confirmMessage = `确定要删除选中的 ${checkboxes.length} 条记录吗?此操作不可撤销。`;
if (!confirm(confirmMessage)) {
return;
}
// 收集选中的文档ID
const docIds = Array.from(checkboxes).map(cb => cb.value);
// 创建表单并提交
const form = document.createElement('form');
form.method = 'POST';
form.action = '/batch_delete';
docIds.forEach(docId => {
const input = document.createElement('input');
input.type = 'hidden';
input.name = 'doc_ids';
input.value = docId;
form.appendChild(input);
});
document.body.appendChild(form);
form.submit();
}
// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
updateSelectedCount();
});
</script>
{% endblock %}

256
templates/edited.html Normal file
View File

@@ -0,0 +1,256 @@
{% extends "base.html" %}
{% block title %}编辑成果信息 - 紫金·稷下薪火·云枢智海师生成果共创系统{% endblock %}
{% block content %}
<style>
/* 基础样式重置 */
* { margin: 0; padding: 0; box-sizing: border-box; }
/* 容器样式 */
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
/* 标题样式 */
h2 {
color: #2c3e50;
border-bottom: 2px solid #3498db;
padding-bottom: 8px;
margin-bottom: 20px;
}
/* 表单样式 */
.form-container {
background: white;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
padding: 30px;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 8px;
font-weight: 600;
color: #2c3e50;
}
.form-group input,
.form-group textarea {
width: 100%;
padding: 12px;
border: 2px solid #e1e8ed;
border-radius: 6px;
font-size: 14px;
transition: border-color 0.3s;
}
.form-group input:focus,
.form-group textarea:focus {
outline: none;
border-color: #3498db;
box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}
.form-group textarea {
resize: vertical;
min-height: 80px;
}
.form-hint {
font-size: 12px;
color: #7f8c8d;
margin-top: 5px;
}
/* 按钮样式 */
.button-group {
display: flex;
gap: 15px;
margin-top: 30px;
}
.btn {
padding: 12px 24px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
text-decoration: none;
display: inline-block;
text-align: center;
}
.btn-primary {
background: linear-gradient(to right, #3498db, #2980b9);
color: white;
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(52, 152, 219, 0.3);
}
.btn-secondary {
background: linear-gradient(to right, #95a5a6, #7f8c8d);
color: white;
}
.btn-secondary:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(149, 165, 166, 0.3);
}
.btn-danger {
background: linear-gradient(to right, #e74c3c, #c0392b);
color: white;
}
.btn-danger:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(231, 76, 60, 0.3);
}
/* 图片预览样式 */
.image-preview {
margin-top: 10px;
text-align: center;
}
.image-preview img {
max-width: 200px;
max-height: 200px;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
/* 错误提示样式 */
.error-message {
color: #e74c3c;
font-size: 12px;
margin-top: 5px;
}
/* 必填字段标记 */
.required {
color: #e74c3c;
}
</style>
<div class="container">
<h2>编辑成果信息</h2>
<div class="form-container">
<form action="{{ url_for('update_entry', doc_id=document._id) }}" method="POST" id="editForm">
{% if document.data %}
{# 从原始数据中解析字段 #}
{% set data_string = document.data %}
{% set pairs = data_string.split('|###|') %}
{% for pair in pairs %}
{% if ':' in pair %}
{% set key_value = pair.split(':', 1) %}
{% set field_key = key_value[0].strip() %}
{% set field_value = key_value[1].strip() %}
{# 处理列表格式 [item1|##|item2] #}
{% if field_value.startswith('[') and field_value.endswith(']') %}
{% set list_content = field_value[1:-1] %}
{% set field_value = list_content.split('|##|')|join(', ') %}
{% endif %}
<div class="form-group">
<label for="field_{{ loop.index }}">{{ field_key }} <span class="required">*</span></label>
<input type="text" id="field_{{ loop.index }}" name="field_{{ loop.index }}" value="{{ field_value }}" required>
<input type="hidden" name="key_{{ loop.index }}" value="{{ field_key }}">
</div>
{% endif %}
{% endfor %}
{% else %}
{# 如果没有data字段显示提示信息 #}
<div class="form-group">
<p style="color: #e74c3c; text-align: center;">该记录没有可编辑的数据</p>
</div>
{% endif %}
{% if document.image %}
<div class="form-group">
<label>原图片预览</label>
<div class="image-preview">
<img src="{{ url_for('serve_image', filename=document.image) }}" alt="原图片" onerror="this.style.display='none'">
</div>
<div class="form-hint">当前关联的图片,编辑时无法修改图片</div>
</div>
{% endif %}
<div class="button-group">
<button type="submit" class="btn btn-primary">保存修改</button>
<a href="{{ url_for('show_all') }}" class="btn btn-secondary">取消返回</a>
<button type="button" class="btn btn-danger" onclick="confirmDelete()">删除记录</button>
</div>
</form>
</div>
</div>
<script>
// 表单验证
document.getElementById('editForm').addEventListener('submit', function(e) {
// 检查所有字段是否都有值
const inputs = document.querySelectorAll('input[type="text"]');
let hasEmptyField = false;
inputs.forEach(input => {
if (!input.value.trim()) {
hasEmptyField = true;
input.style.borderColor = '#e74c3c';
} else {
input.style.borderColor = '#e1e8ed';
}
});
if (hasEmptyField) {
e.preventDefault();
alert('所有字段都必须填写!');
return false;
}
return true;
});
// 删除确认
function confirmDelete() {
if (confirm('确定要删除这条记录吗?此操作不可撤销!')) {
// 创建删除表单并提交
const form = document.createElement('form');
form.method = 'POST';
form.action = '{{ url_for("delete_entry", doc_id=document._id) }}';
document.body.appendChild(form);
form.submit();
}
}
// 自动格式化逗号分隔的值
document.querySelectorAll('input[type="text"]').forEach(input => {
input.addEventListener('blur', function(e) {
const value = e.target.value.trim();
if (value && value.includes(',')) {
// 格式化逗号分隔的值
const formatted = value
.split(',')
.map(item => item.trim())
.filter(item => item)
.join(', ');
e.target.value = formatted;
}
});
});
</script>
{% endblock %}