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

如何在Django博客发布页的分类下拉菜单中添加新增分类按钮

实现步骤

1. 后端新增分类接口

首先在你的views.py中新增视图,用于处理分类创建请求:

from django.http import JsonResponse
from .models import category
from django.contrib.auth.decorators import login_required

@login_required
def add_category(request):
    if request.method == "POST":
        cat_name = request.POST.get("name", "").strip()
        if not cat_name:
            return JsonResponse({"status": "error", "msg": "分类名称不能为空"})
        if category.objects.filter(name__iexact=cat_name).exists():
            return JsonResponse({"status": "error", "msg": "该分类已存在"})
        new_cat = category.objects.create(name=cat_name)
        return JsonResponse({"status": "success", "id": new_cat.id, "name": new_cat.name})
    return JsonResponse({"status": "error", "msg": "请求方式错误"})

之后在urls.py中添加对应路由:

path('add-category/', views.add_category, name='add_category'),

2. 模板端修改

不需要修改原有表单定义,直接在现有模板底部追加JS逻辑,实现下拉框新增选项和分类创建交互:

{% if user.is_authenticated %}
<h1>Add Post...</h1>
<br/><br/>
<div class="form-group">
<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.media }}
    {{ form|crispy}}
    <br>
    <button class="btn btn-secondary btn-lg">Post</button>
</form>
</div>
{% endif %}

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 获取分类下拉框
    const catSelect = document.querySelector('select[name="category"]');
    // 添加「新增分类」选项
    const addOption = document.createElement('option');
    addOption.value = "add_new";
    addOption.text = "+ 新增分类";
    catSelect.add(addOption);

    // 监听下拉框选择事件
    catSelect.addEventListener('change', function() {
        if (this.value === "add_new") {
            const newCatName = prompt("请输入新分类名称:");
            if (!newCatName || newCatName.trim() === "") {
                this.selectedIndex = 0;
                return;
            }
            // 提交请求到后端创建分类
            fetch("{% url 'add_category' %}", {
                method: "POST",
                headers: {
                    "X-CSRFToken": document.querySelector('input[name="csrfmiddlewaretoken"]').value,
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                body: `name=${encodeURIComponent(newCatName.trim())}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.status === "success") {
                    // 把新分类插入下拉框并自动选中
                    const newOption = document.createElement('option');
                    newOption.value = data.id;
                    newOption.text = data.name;
                    catSelect.insertBefore(newOption, addOption);
                    newOption.selected = true;
                } else {
                    alert(data.msg);
                    this.selectedIndex = 0;
                }
            })
            .catch(err => {
                alert("新增分类失败,请重试");
                this.selectedIndex = 0;
            })
        }
    })
})
</script>

3. 可选优化

如果需要更好的视觉效果,可以把原生prompt替换为Bootstrap模态框,和现有页面样式保持统一;如果分类需要更多字段(比如分类描述),对应调整弹窗表单和后端视图即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:48:03