gpt4 book ai didi

Django Admin,如何根据另一个选择填充选择选项

转载 作者:行者123 更新时间:2023-12-04 14:23:11 25 4
gpt4 key购买 nike

我的场景:

我有三个表,类别,子类别,产品。
插入新产品时,有两个选择框

1)第一个选择用于类别(其工作)

2)第二个是子类别,它应该与第一个选择相关。需要从子类别表中获取数据。

子类别表将类别 id 作为外键。
我是初学者,请有人帮助。

最佳答案

You will have to use some JS library I prefer JQuery.



要填充此子类别字段,您必须创建一个 View ,该 View 将使用 json 数据进行响应。
from django.http import HttpResponse
import json

def get_subcategory(request):
id = request.GET.get('id','')
result = list(Subcategory.objects.filter(category_id=int(id)).values('id', 'name'))
return HttpResponse(json.dumps(result), content_type="application/json")

在 urls.py 你需要添加一个模式来访问 View :
url(r'^/getSubcategory/$', views.get_subcategory) 

现在你必须覆盖 change_from.html django admin 为您的产品应用程序添加一些 JS 代码来实现魔法。
your_project
|-- your_project/
|-- myapp/
|-- templates/
|-- admin/
|-- myapp/
|-- change_form.html # do not misspell this

Note: The location of this file is not important. You can put it inside your app and it will still work. As long as its location can be discovered by django. What's more important is the name of the HTML file has to be the same as the original HTML file name provided by django.



在您的 change_form.html ,这样写:
{% extends "admin/change_form.html" %} 

{% block extrahead %}
{{ block.super }}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(function(){
// inspect html to check id of category select dropdown.
$(document).on('change', "select#id_category", function(){
$.getJSON("/getSubcategory/",{id: $(this).val()}, function(j){
var options = '<option value="">---------</option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
}
// inspect html to check id of subcategory select dropdown.
$("select#id_subcategory").html(options);
});
});
});
</script>
{% endblock %}
# Create a JS file and put this second script tag in it, that way will be easier to maintain your template.

关于Django Admin,如何根据另一个选择填充选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47843241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com