You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中实现点击保存按钮存储单个专家JSON对象

实现专家数据保存到数据库的完整流程

前端处理逻辑

  • 渲染专家列表时,把每个专家的JSON对象转成字符串,绑定到「保存」按钮的自定义属性(比如data-expert)上,或者在循环时直接把数据挂载到按钮的点击事件里:
    <!-- 示例:Jinja2模板循环渲染 -->
    {% for expert in experts %}
      <div class="expert-card">
        <h3>{{ expert.name }}</h3>
        <p>{{ expert.field }}</p>
        <button class="save-btn" data-expert='{{ expert | tojson }}'>保存</button>
      </div>
    {% endfor %}
    
  • 用JavaScript监听按钮点击事件,获取专家数据并发起POST请求:
    document.querySelectorAll('.save-btn').forEach(btn => {
      btn.addEventListener('click', async () => {
        const expertData = JSON.parse(btn.dataset.expert);
        try {
          const response = await fetch('/save-expert/', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              // 如果用Django,还要加CSRF令牌
              'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
            },
            body: JSON.stringify(expertData)
          });
          if (response.ok) {
            alert('保存成功');
            btn.disabled = true; // 防止重复点击
          } else {
            alert('保存失败,请重试');
          }
        } catch (err) {
          console.error('请求出错:', err);
        }
      });
    });
    

后端URL配置与数据存储

以Flask为例

  1. 配置URL路由:
    from flask import Flask, request, jsonify
    from your_models import Expert  # 导入你的数据库模型
    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    db = SQLAlchemy(app)
    
    # 定义保存专家的POST接口
    @app.route('/save-expert/', methods=['POST'])
    def save_expert():
        try:
            expert_data = request.get_json()
            # 检查是否已存在该专家(根据唯一标识,比如id)
            existing_expert = Expert.query.filter_by(id=expert_data['id']).first()
            if existing_expert:
                return jsonify({'status': 'error', 'msg': '该专家已存在'}), 400
            # 创建新的专家记录
            new_expert = Expert(
                id=expert_data['id'],
                name=expert_data['name'],
                field=expert_data['field'],
                bio=expert_data.get('bio', '')
            )
            db.session.add(new_expert)
            db.session.commit()
            return jsonify({'status': 'success', 'msg': '保存成功'}), 201
        except Exception as e:
            db.session.rollback()
            return jsonify({'status': 'error', 'msg': str(e)}), 500
    

以Django为例

  1. 配置URL模式(在urls.py中):
    from django.urls import path
    from . import views
    
    urlpatterns = [
        # 其他URL
        path('save-expert/', views.save_expert, name='save_expert'),
    ]
    
  2. 编写视图函数(在views.py中):
    from django.http import JsonResponse
    from django.views.decorators.csrf import csrf_exempt  # 生产环境推荐用正规CSRF验证
    from .models import Expert
    import json
    
    @csrf_exempt
    def save_expert(request):
        if request.method == 'POST':
            try:
                expert_data = json.loads(request.body)
                # 检查重复
                if Expert.objects.filter(id=expert_data['id']).exists():
                    return JsonResponse({'status': 'error', 'msg': '专家已存在'}, status=400)
                # 创建记录
                Expert.objects.create(
                    id=expert_data['id'],
                    name=expert_data['name'],
                    field=expert_data['field'],
                    bio=expert_data.get('bio', '')
                )
                return JsonResponse({'status': 'success', 'msg': '保存成功'}, status=201)
            except Exception as e:
                return JsonResponse({'status': 'error', 'msg': str(e)}, status=500)
        return JsonResponse({'status': 'error', 'msg': '仅支持POST请求'}, status=405)
    

关键注意事项

  • 数据验证:必须对前端传入的JSON数据做合法性校验,比如必填字段是否存在、数据类型是否正确,避免脏数据存入数据库。
  • 重复保存控制:利用专家的唯一标识(比如API返回的id字段)做重复判断,防止同一位专家被多次存储。
  • CSRF防护:如果是前后端不分离的架构,一定要配置CSRF令牌验证,避免跨站请求伪造攻击。
  • 错误处理:前端和后端都要做异常捕获,给出明确的错误提示,方便排查问题。

内容的提问来源于stack exchange,提问作者SIM777

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 23:15:22