Compare commits

...

3 Commits

Author SHA1 Message Date
彭森 691993373d commit 1. 编辑/新增模态框 2. input新增date和month 2024-06-02 14:07:08 +08:00
彭森 d5a3a9d0a5 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	application/perf_mgnt/views.py
#	templates/upload_excel_modal.html
2024-06-02 13:44:20 +08:00
彭森 be08a5c38a commit 1. 编辑/新增模态框 2. input新增date和month 2024-06-02 13:38:07 +08:00
7 changed files with 425 additions and 464 deletions

View File

@ -135,8 +135,8 @@ DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'xh_digital_manage', # 数据库名
'USER': 'wsc', # 用户名
'PASSWORD': 'jsxh9512..', # 密码
'USER': 'ps', # 用户名
'PASSWORD': 'ps240523..', # 密码
'HOST': 'bj-cdb-7qxczedm.sql.tencentcdb.com', # 地址
'PORT': '59450', # 端口号
'OPTIONS': {

View File

@ -28,7 +28,7 @@
<!-- 按钮 -->
<div class="col-md-4 mt-4 text-end">
<button class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#modifyRecordsModal">修改记录</button>
<button class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#addModal">添加</button>
<button class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#addModifyModal">添加</button>
<button class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#downloadModal">导出</button>
<button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#uploadModal">上传Excel</button>
</div>
@ -64,222 +64,7 @@
<!-- 模态框 -->
{% include 'modify_record_modal.html' with modify_records_url=modify_records_url %}
{% include 'upload_excel_modal.html' with parse_excel_url=common_excel_parse download_template_url=download_template_url upload_excel_preview_config=upload_excel_preview_config %}
<div id="addModal" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog"
aria-labelledby="addModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-xl" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addModalCenterTitle">添加/编辑</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="groupBusinessTargetForm">
{% csrf_token %}
<!-- 使用row和col来控制标签的布局 -->
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="primary_department">一级部门</label>
<select class="form-control" id="primary_department_add" name="primary_department"
required>
<option value="">选择部门</option>
<option value="天信">天信</option>
<option value="混改">混改</option>
<option value="艾力芬特">艾力芬特</option>
<option value="星河">星河</option>
<option value="星海">星海</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="year">年份</label>
<select class="form-control" id="year_add" name="year" required>
<option value="">选择年度</option>
<option value="2024">2024</option>
<option value="2023">2023</option>
<option value="2022">2022</option>
<option value="2021">2021</option>
<option value="2020">2020</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="project_nature">项目性质</label>
<select class="form-control" id="project_nature_add" name="project_nature" required>
<option value="">选择项目性质</option>
<option value="新增">新增</option>
<option value="存续">存续</option>
<option value="新增及存续">新增及存续</option>
<option value="老客户新业务">老客户新业务</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="form-control" for="sales">销售额(元)</label>
<input type="number" class="form-control" id="sales_add" name="sales"
required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control" for="total_revenue_target">收入总目标(元)</label>
<input type="number" class="form-control" id="total_revenue_target_add"
name="total_revenue_target" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control" for="new_revenue_target">新增收入目标(元)</label>
<input type="number" class="form-control" id="new_revenue_target_add"
name="new_revenue_target"
required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="form-control" for="existing_revenue_target">存量收入目标(元)</label>
<input type="number" class="form-control" id="existing_revenue_target_add"
name="existing_revenue_target" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control" for="cost_limit">成本限额(元)</label>
<input type="number" class="form-control" id="cost_limit_add" name="cost_limit"
required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control" for="gross_profit">毛利润(元)</label>
<input type="number" class="form-control" id="gross_profit_add" name="gross_profit"
required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="form-control" for="expense_limit">费用限额(元)</label>
<input type="number" class="form-control" id="expense_limit_add"
name="expense_limit"
required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control" for="operating_profit">营业利润(元)</label>
<input type="number" class="form-control" id="operating_profit_add"
name="operating_profit"
required>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-bs-dismiss="modal" id="submitForm">添加</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
</div>
</div>
</div>
</div>
<div id="modifyModal" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog"
aria-labelledby="modifyModal" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-xl" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addModalCenterTitle">修改</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="groupBusinessTargetForm">
{% csrf_token %}
<!-- 使用row和col来控制标签的布局 -->
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="primary_department">一级部门</label>
<input class="form-control" id="primary_department_modify" name="primary_department"
required disabled>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="year">年度</label>
<input class="form-control" id="year_modify" name="year"
required disabled>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="project_nature">项目性质</label>
<input class="form-control" id="project_nature_modify" name="project_nature"
required disabled>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label class="form-label" for="modified_field">修改字段</label>
<select class="form-control" id="modified_field" name="modified_field" required>
<option value="">选择修改字段</option>
<option value="销售额">销售额</option>
<option value="收入总目标">收入总目标</option>
<option value="新增收入目标">新增收入目标</option>
<option value="存量收入目标">存量收入目标</option>
<option value="成本限额">成本限额</option>
<option value="毛利润">毛利润</option>
<option value="费用限额">费用限额</option>
<option value="营业利润">营业利润</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="form-label" for="old_value">旧值</label>
<input class="form-control" id="old_value" name="old_value"
required disabled>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="form-label" for="new_value">新值</label>
<input class="form-control" id="new_value" name="new_value"
required>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="form-label" for="modified_by">修改人</label>
<input class="form-control" id="modified_by" name="modified_by"
required>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-bs-dismiss="modal" id="submitModifyForm">确定
</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
</div>
</div>
</div>
</div>
{% include 'add_modify_modal.html' with modify_records_url=modify_records_url add_records_url=add_records_url %}
<!-- 模态框结束 -->
{% endblock %}

View File

@ -5,6 +5,8 @@ urlpatterns = [
# 集团经营目标
path('gbo_list/', gbo_list_view, name='gbo_list'),
path('gbo_audit_record_list/', gbo_audit_record_list_view, name='gbo_audit_record_list'),
path('add_gbo/', add_gbo_data, name='add_gbo_data'),
path('modify_gbo/', modify_gbo_data, name='modify_gbo_data'),
# 员工业绩目标
path('emt_list/', emt_list_view, name='emt_list'),
path('emt_audit_record_list/', emt_audit_record_list_view, name='emt_audit_record_list'),

View File

@ -1,8 +1,8 @@
import json
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import JsonResponse
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.http import require_POST
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
@ -103,8 +103,11 @@ def gbo_list_view(request):
{'header': '营业利润(元)', 'field': 'operating_profit'},
{'header': '操作', 'field': 'actions'},
],
'modify_url': reverse('modify_gbo_data'),
'add_url': reverse('add_gbo_data'),
"modify_records_url": reverse('gbo_audit_record_list'),
'download_template_url': reverse('download_excel_template', kwargs={'template_name': '业绩管理-集团经营目标-Excel上传模板.xlsx'}),
'download_template_url': reverse('download_excel_template',
kwargs={'template_name': '业绩管理-集团经营目标-Excel上传模板.xlsx'}),
"common_excel_parse": reverse("common_excel_parse"),
"upload_excel_preview_config": {
"columns": [
@ -121,45 +124,125 @@ def gbo_list_view(request):
{'header': '营业利润(元)'},
],
"rows": {
"primary_department": {"type": "select",'width': '180px', "options": ['天信', '混改', '艾力芬特', '星河', '星海']},
"year": {"type": "select",'width': '180px', "options": ['2024', '2023', '2022', '2021', '2020']},
"project_nature": {"type": "select",'width': '180px', "options": ['新增', '存续', '新增及存续', '老客户新业务']},
"sales": {"type": "text", 'width': '180px',},
"total_revenue_target": {"type": "text", 'width': '180px',},
"new_revenue_target": {"type": "text", 'width': '180px',},
"existing_revenue_target": {"type": "text", 'width': '180px',},
"cost_limit": {"type": "text", 'width': '180px',},
"gross_profit": {"type": "text", 'width': '180px',},
"expense_limit": {"type": "text", 'width': '180px',},
"operating_profit": {"type": "text", 'width': '180px',},
"primary_department": {"type": "select", 'width': '180px',
"options": ['天信', '混改', '艾力芬特', '星河', '星海']},
"year": {"type": "select", 'width': '180px', "options": ['2024', '2023', '2022', '2021', '2020']},
"project_nature": {"type": "select", 'width': '180px',
"options": ['新增', '存续', '新增及存续', '老客户新业务']},
"sales": {"type": "text", 'width': '180px', },
"total_revenue_target": {"type": "text", 'width': '180px', },
"new_revenue_target": {"type": "text", 'width': '180px', },
"existing_revenue_target": {"type": "text", 'width': '180px', },
"cost_limit": {"type": "text", 'width': '180px', },
"gross_profit": {"type": "text", 'width': '180px', },
"expense_limit": {"type": "text", 'width': '180px', },
"operating_profit": {"type": "text", 'width': '180px', },
}
},
'model_info': json.dumps(
{
'app_label': 'perf_mgnt', # 应用名
'model_name': 'GroupBusinessTarget', # 模型名
'unique_together_fields': [
'primary_department',
'year',
'project_nature',
'project_nature',
'sales',
'total_revenue_target',
'new_revenue_target',
'existing_revenue_target',
'cost_limit',
'gross_profit',
'expense_limit',
'operating_profit'
], # 用于确定唯一记录的字段列表
'form_fields_config': {
"fields": {
"primary_department": {"type": "select", 'label': '一级部门',
'options': ['天信', '混改', '艾力芬特', '星河', '星海']},
"year": {"type": "select", 'label': '年份', 'options': ['2024', '2023', '2022', '2021', '2020']},
"project_nature": {"type": "select", 'label': '项目性质',
'options': ['新增', '存续', '新增及存续', '老客户新业务']},
"sales": {"type": "text", 'label': '销售额(元)'},
"total_revenue_target": {"type": "text", 'label': '收入总目标(元)'},
"new_revenue_target": {"type": "text", 'label': '新增收入目标(元)'},
"existing_revenue_target": {"type": "text", 'label': '存量收入目标(元)'},
"cost_limit": {"type": "text", 'label': '成本限额(元)'},
"gross_profit": {"type": "text", 'label': '毛利润(元)'},
"expense_limit": {"type": "text", 'label': '费用限额(元)'},
"operating_profit": {"type": "text", 'label': '营业利润(元)'},
}
),
'save_data_url': reverse('save_excel_table_data'), # 用于保存数据的URL
}
}
return render(request, 'perf_mgnt/gbo_list.html', context)
def add_gbo_data(request):
"""
添加集团经营目标数据
"""
# 获取表单数据
primary_department = request.POST.get('primary_department')
year = request.POST.get('year')
project_nature = request.POST.get('project_nature')
sales = request.POST.get('sales')
total_revenue_target = request.POST.get('total_revenue_target')
new_revenue_target = request.POST.get('new_revenue_target')
existing_revenue_target = request.POST.get('existing_revenue_target')
cost_limit = request.POST.get('cost_limit')
gross_profit = request.POST.get('gross_profit')
expense_limit = request.POST.get('expense_limit')
operating_profit = request.POST.get('operating_profit')
# 创建新的集团经营目标数据
new_gbo_data = GroupBusinessTarget(
primary_department=primary_department,
year=year,
project_nature=project_nature,
sales=sales,
total_revenue_target=total_revenue_target,
new_revenue_target=new_revenue_target,
existing_revenue_target=existing_revenue_target,
cost_limit=cost_limit,
gross_profit=gross_profit,
expense_limit=expense_limit,
operating_profit=operating_profit
)
new_gbo_data.save()
# 返回添加成功的消息
return JsonResponse({'message': '添加成功'})
def modify_gbo_data(request):
"""
修改集团经营目标数据
"""
try:
# 获取表单数据
target_id = request.POST.get('target_id')
primary_department = request.POST.get('primary_department')
year = request.POST.get('year')
project_nature = request.POST.get('project_nature')
sales = request.POST.get('sales')
total_revenue_target = request.POST.get('total_revenue_target')
new_revenue_target = request.POST.get('new_revenue_target')
existing_revenue_target = request.POST.get('existing_revenue_target')
cost_limit = request.POST.get('cost_limit')
gross_profit = request.POST.get('gross_profit')
expense_limit = request.POST.get('expense_limit')
operating_profit = request.POST.get('operating_profit')
# 获取需要修改的对象
target = GroupBusinessTarget.objects.get(target_id=target_id)
# 修改数据
target.primary_department = primary_department
target.year = year
target.project_nature = project_nature
target.sales = sales
target.total_revenue_target = total_revenue_target
target.new_revenue_target = new_revenue_target
target.existing_revenue_target = existing_revenue_target
target.cost_limit = cost_limit
target.gross_profit = gross_profit
target.expense_limit = expense_limit
target.operating_profit = operating_profit
# 保存修改
target.save()
return JsonResponse({'message': '修改成功'}, status=200)
except GroupBusinessTarget.DoesNotExist:
return JsonResponse({'message': '记录不存在'}, status=404)
except Exception as e:
return JsonResponse({'message': '修改失败', 'error': str(e)}, status=400)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def gbo_audit_record_list_view(request):

View File

@ -0,0 +1,112 @@
{% load static %}
<div id="addModifyModal" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog"
aria-labelledby="formModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-xl" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="formModalTitle"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="formModalForm">
{% csrf_token %}
<input type="hidden" id="operationType" name="operation_type">
<input type="hidden" id="target_id" name="target_id">
{% for field, config in form_fields_config.fields.items %}
{% if forloop.first or forloop.counter|add:"-1"|divisibleby:"3" %}
<div class="row mb-3">
{% endif %}
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="{{ field }}">{{ config.label }}</label>
{% if config.type == 'text' %}
<input type="text" class="form-control" id="{{ field }}" name="{{ field }}">
{% elif config.type == 'select' %}
<select class="form-control" id="{{ field }}" name="{{ field }}">
{% for option in config.options %}
<option value="{{ option }}">{{ option }}</option>
{% endfor %}
</select>
{% endif %}
</div>
</div>
{% if forloop.counter|divisibleby:"3" or forloop.last %}
</div>
{% endif %}
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="submitForm">提交</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
</div>
</div>
</div>
</div>
<script>
function openFormModal(operationType, record = null) {
$('#operationType').val(operationType);
if (operationType === 'add') {
$('#formModalTitle').text('添加');
$('#formModalForm').trigger('reset');
$('#target_id').val('');
} else if (operationType === 'modify' && record) {
$('#formModalTitle').text('修改');
$('#target_id').val(record.target_id);
{% for field in form_fields_config.fields.keys %}
$('#{{ field }}').val(record['{{ field }}']);
{% endfor %}
}
$('#addModifyModal').modal('show');
}
$(document).ready(function () {
$('.edit-btn').on('click', function () {
var record = {
target_id: $(this).data('target_id')
};
{% for field in form_fields_config.fields.keys %}
record['{{ field }}'] = $(this).data('{{ field }}');
{% endfor %}
openFormModal('modify', record);
});
$('#submitForm').on('click', function () {
var operationType = $('#operationType').val();
var formData = $('#formModalForm').serialize();
var url = operationType === 'modify' ? '{% url "modify_gbo_data" %}' : '{% url "add_gbo_data" %}';
$.ajax({
type: 'POST',
url: url,
data: formData,
success: function (response) {
$('#addModifyModal').modal('hide');
if (operationType === 'modify') {
alert('修改成功');
} else {
alert('添加成功');
}
location.reload(); // 刷新页面
},
error: function (response) {
alert('操作失败,请重试。');
}
});
});
// 当模态框关闭时,重置表单
$('#addModifyModal').on('hidden.bs.modal', function () {
$('#formModalForm').trigger('reset');
$('#formModalTitle').text('');
$('#target_id').val('');
$('#operationType').val('');
{% for field in form_fields_config.fields.keys %}
$('#{{ field }}').val('');
{% endfor %}
});
});
</script>

View File

@ -6,28 +6,32 @@
<thead>
<tr>
{% for column in table_columns %}
<th>{{ column.header }}</th>
<th>{{ column.header }}</th>
{% endfor %}
</tr>
</thead>
<tbody id="result" style="color: white;">
{% for item in items %}
{% for item in items %}
<tr>
{% for column in table_columns %}
{% if column.field == 'actions' %}
<td>
<a href="#">编辑</a>
</td>
<td>
<a href="#" class="edit-btn" data-target_id="{{ item.target_id }}"
{% for field, config in form_fields_config.fields.items %}
data-{{ field }}="{{ item|getattr_filter:field }}"
{% endfor %}
data-bs-toggle="modal" data-bs-target="#addModifyModal">编辑</a>
</td>
{% else %}
<td>{{ item|getattr_filter:column.field }}</td>
<td>{{ item|getattr_filter:column.field }}</td>
{% endif %}
{% endfor %}
</tr>
{% empty %}
{% empty %}
<tr>
<td class="text-center" colspan="{{ table_columns|length }}">暂无数据</td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
</div>

View File

@ -1,4 +1,5 @@
<div id="uploadModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="uploadModalLabel" aria-hidden="true">
<div id="uploadModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="uploadModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
@ -22,7 +23,8 @@
</div>
</div>
<div id="excelPreviewModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="excelPreviewModalTitle" aria-hidden="true">
<div id="excelPreviewModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="excelPreviewModalTitle"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-xl" role="document">
<div class="modal-content">
<div class="modal-header">
@ -33,13 +35,13 @@
<div style="overflow-x: auto;">
<table id="form-input-table" class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th>序号</th>
<!-- ... 其他标题列 ... -->
</tr>
<tr>
<th>序号</th>
<!-- ... 其他标题列 ... -->
</tr>
</thead>
<tbody>
<!-- 表格内容将通过JavaScript动态填充 -->
<!-- 表格内容将通过JavaScript动态填充 -->
</tbody>
</table>
</div>
@ -50,219 +52,192 @@
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
<button id="saveButton" type="button" class="btn btn-primary" data-bs-dismiss="modal">保存</button>
<button type="button" class="btn btn-primary" data-bs-dismiss="modal">关闭</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
// 当模态框打开时清空文件输入和文件名显示
$('#uploadModal').on('show.bs.modal', function() {
$('#inputFile').val(''); // 清空文件输入
$('#file-chosen').text('未选择文件'); // 重置文件名显示
});
// 当选择文件变化时,更新文件名显示
$('#inputFile').on('change', function() {
var fileName = $(this).val().split('\\').pop();
$('#file-chosen').text(fileName || '未选择文件');
});
// 每页显示的行数
var rowsPerPage = 10;
var currentPage = 1;
var tableData = [];
// 处理上传按钮的点击事件
$('#uploadBtn').on('click', function() {
var formData = new FormData($('#upload-form')[0]);
if ($('#inputFile').get(0).files.length === 0) {
alert("没有文件选中");
return;
}
$.ajax({
url: '{{ parse_excel_url }}',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(response) {
// 隐藏上传模态框
$('#uploadModal').modal('hide');
// 获取表头和表体的jQuery对象
var tableHead = $('#form-input-table thead');
var tableBody = $('#form-input-table tbody');
// 清空现有的表头和表体内容
tableHead.empty();
tableBody.empty();
// 从Django模板上下文传递配置到JavaScript
var upload_excel_preview_config = {{ upload_excel_preview_config|safe }};
// 使用从服务器返回的数据来构造表头
var headerRow = $('<tr>'); // 创建表头行
headerRow.append($('<th>').text('序号')); // 添加序号标题
$.each(upload_excel_preview_config.columns, function(index, column) {
headerRow.append($('<th>').text(column.header)); // 添加其他标题列,设置宽度
});
tableHead.append(headerRow); // 将表头行添加到表头中
// 存储数据以进行分页
tableData = response;
// 初始化分页信息
currentPage = 1;
updateTable();
// 显示数据预览模态框
$('#excelPreviewModal').modal('show');
},
error: function(xhr, status, error) {
// 上传失败的回调函数
// 错误处理...
}
});
});
// 更新表格内容,处理分页按钮的点击事件
function updateTable() {
var tableBody = $('#form-input-table tbody');
tableBody.empty(); // 清空表体内容
var upload_excel_preview_config = {{ upload_excel_preview_config|safe }};
var startIndex = (currentPage - 1) * rowsPerPage;
var endIndex = startIndex + rowsPerPage;
var pageData = tableData.slice(startIndex, endIndex);
// 遍历分页数据行
$.each(pageData, function(index, rowData) {
var row = $('<tr>'); // 创建新的行元素
row.append($('<td>').text(startIndex + index + 1)); // 添加序号列
var cellIndex = 0; // 初始化列索引
// 为每个单元格创建对应的输入框或下拉菜单
$.each(upload_excel_preview_config.rows, function(key, cell) {
var cellElement;
var cellValue = rowData[cellIndex] || ''; // 通过列索引获取值
if (cell.type === 'text') {
// 创建输入框
cellElement = $('<input>').attr({
style: "width: " + cell.width,
type: 'text',
class: 'form-control',
id: key,
name: key,
value: cellValue,
});
} else if(cell.type === 'select') {
// 创建下拉菜单
cellElement = $('<select>').attr({
style: "width: " + cell.width,
class: 'form-control',
id: key,
name: key,
});
// 添加选项
$.each(cell.options, function(optionIndex, optionValue) {
var optionElement = $('<option>').val(optionValue).text(optionValue);
if(cellValue === optionValue) {
optionElement.attr('selected', 'selected');
}
cellElement.append(optionElement);
});
}
// 将输入框或下拉菜单添加到单元格中
var td = $('<td>').append(cellElement);
row.append(td);
cellIndex++; // 增加列索引
$(document).ready(function () {
// 当模态框打开时清空文件输入和文件名显示
$('#uploadModal').on('show.bs.modal', function () {
$('#inputFile').val(''); // 清空文件输入
$('#file-chosen').text('未选择文件'); // 重置文件名显示
});
tableBody.append(row); // 将新的行元素添加到表体中
});
// 当选择文件变化时,更新文件名显示
$('#inputFile').on('change', function () {
var fileName = $(this).val().split('\\').pop();
$('#file-chosen').text(fileName || '未选择文件');
});
// 更新分页信息
$('#pageInfo').text('第 ' + currentPage + ' 页, 共 ' + Math.ceil(tableData.length / rowsPerPage) + ' 页');
}
$('#prevPage').on('click', function() {
if (currentPage > 1) {
currentPage--;
updateTable();
}
});
$('#nextPage').on('click', function() {
if (currentPage < Math.ceil(tableData.length / rowsPerPage)) {
currentPage++;
updateTable();
}
});
});
</script>
<script>
// 从Django模板获取model_info和save_data_url
var modelInfo = JSON.parse('{{ model_info|safe }}');
var saveDataUrl = '{{ save_data_url }}';
$(document).ready(function() {
$('#saveButton').on('click', function() {
// 每页显示的行数
var rowsPerPage = 10;
var currentPage = 1;
var tableData = [];
// 遍历表格每一行
$('#excelPreviewModal table tbody tr').each(function() {
var rowData = {};
// 处理上传按钮的点击事件
$('#uploadBtn').on('click', function () {
var formData = new FormData($('#upload-form')[0]);
if ($('#inputFile').get(0).files.length === 0) {
alert("没有文件选中");
return;
}
$.ajax({
url: '{{ parse_excel_url }}',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function (response) {
// 隐藏上传模态框
$('#uploadModal').modal('hide');
// 遍历当前行的每个单元格
$(this).find('td').each(function() {
var input = $(this).find('input');
var select = $(this).find('select');
// 检查单元格内是否有 input 或 select 元素,并使用它们的 name 属性作为键
if (input.length) {
var inputName = input.attr('name');
rowData[inputName] = input.val();
} else if (select.length) {
var selectName = select.attr('name');
rowData[selectName] = select.val();
// 获取表头和表体的jQuery对象
var tableHead = $('#form-input-table thead');
var tableBody = $('#form-input-table tbody');
// 清空现有的表头和表体内容
tableHead.empty();
tableBody.empty();
// 从Django模板上下文传递配置到JavaScript
var upload_excel_preview_config = {{ upload_excel_preview_config|safe }};
// 使用从服务器返回的数据来构造表头
var headerRow = $('<tr>'); // 创建表头行
headerRow.append($('<th>').text('序号')); // 添加序号标题
$.each(upload_excel_preview_config.columns, function (index, column) {
headerRow.append($('<th>').text(column.header)); // 添加其他标题列,设置宽度
});
tableHead.append(headerRow); // 将表头行添加到表头中
// 存储数据以进行分页
tableData = response;
// 初始化分页信息
currentPage = 1;
updateTable();
// 显示数据预览模态框
$('#excelPreviewModal').modal('show');
},
error: function (xhr, status, error) {
// 上传失败的回调函数
// 错误处理...
}
});
tableData.push(rowData);
});
// 构建发送到后端的数据对象
var postData = {
app_label: modelInfo.app_label,
model_name: modelInfo.model_name,
unique_together_fields: modelInfo.unique_together_fields,
table_data: tableData
};
// 更新表格内容,处理分页按钮的点击事件
function updateTable() {
var tableBody = $('#form-input-table tbody');
tableBody.empty(); // 清空表体内容
// 发送AJAX请求到后端保存数据
$.ajax({
url: saveDataUrl, // 使用从Django模板中获取的URL
method: 'POST',
contentType: 'application/json',
data: JSON.stringify(postData),
success: function(response) {
console.log('数据保存成功', response);
// 处理成功响应
},
error: function(xhr, status, error) {
console.error('保存数据时出错', error);
// 处理错误响应
var upload_excel_preview_config = {{ upload_excel_preview_config|safe }};
var startIndex = (currentPage - 1) * rowsPerPage;
var endIndex = startIndex + rowsPerPage;
var pageData = tableData.slice(startIndex, endIndex);
// 遍历分页数据行
$.each(pageData, function (index, rowData) {
var row = $('<tr>'); // 创建新的行元素
row.append($('<td>').text(startIndex + index + 1)); // 添加序号列
var cellIndex = 0; // 初始化列索引
// 为每个单元格创建对应的输入框或下拉菜单
$.each(upload_excel_preview_config.rows, function (key, cell) {
var cellElement;
var cellValue = rowData[cellIndex] || ''; // 通过列索引获取值
if (cell.type === 'text') {
// 创建输入框
cellElement = $('<input>').attr({
style: "width: " + cell.width,
type: 'text',
class: 'form-control',
id: key,
name: key,
value: cellValue,
});
} else if (cell.type === 'select') {
// 创建下拉菜单
cellElement = $('<select>').attr({
style: "width: " + cell.width,
class: 'form-control',
id: key,
name: key,
});
// 添加选项
$.each(cell.options, function (optionIndex, optionValue) {
var optionElement = $('<option>').val(optionValue).text(optionValue);
if (cellValue === optionValue) {
optionElement.attr('selected', 'selected');
}
cellElement.append(optionElement);
});
} else if (cell.type === 'date') {
// 创建日期选择框
cellElement = $('<input>').attr({
style: "width: " + cell.width,
type: 'date',
class: 'form-control',
id: key,
name: key,
value: cellValue,
});
} else if (cell.type === 'month') {
// 创建月份选择框
cellElement = $('<input>').attr({
style: "width: " + cell.width,
type: 'month',
class: 'form-control',
id: key,
name: key,
value: cellValue,
});
} else if (cell.type === 'number') {
// 创建数字输入框
cellElement = $('<input>').attr({
style: "width: " + cell.width,
type: 'number',
class: 'form-control',
id: key,
name: key,
value: cellValue,
});
}
// 将输入框或下拉菜单添加到单元格中
var td = $('<td>').append(cellElement);
row.append(td);
cellIndex++; // 增加列索引
});
tableBody.append(row); // 将新的行元素添加到表体中
});
// 更新分页信息
$('#pageInfo').text('第 ' + currentPage + ' 页, 共 ' + Math.ceil(tableData.length / rowsPerPage) + ' 页');
}
$('#prevPage').on('click', function () {
if (currentPage > 1) {
currentPage--;
updateTable();
}
});
$('#nextPage').on('click', function () {
if (currentPage < Math.ceil(tableData.length / rowsPerPage)) {
currentPage++;
updateTable();
}
});
});
});
</script>