gpt4 book ai didi

javascript - Django admin 中的自定义相关下拉菜单

转载 作者:行者123 更新时间:2023-12-04 11:30:48 27 4
gpt4 key购买 nike

我有一个按阶段模型的项目外键。我很难在我的 Django 管理页面中创建一个依赖下拉列表。

当用户从该项目的(项目下拉)阶段选择一个项目时,我想在第二个下拉菜单中显示

实现这一目标的最佳方法是什么?

如果下拉菜单根据其父项的值过滤项目,那就太好了。

enter image description here

class Project(models.Model):
name = models.CharFieldmax_length = 100, unique= True)
short_name = models.CharField(max_length= 4, unique= True)
slug = models.SlugField(max_length= 100, allow_unicode=True, null=True, editable= False)
location = models.OneToOneField(Location, on_delete = models.SET_NULL, null= True, blank= False, verbose_name= 'موقعیت')
start_date = models.DateField(default= timezone.now, null= True, blank= True)
end_date = models.DateField(default= timezone.now, null= True, blank= True)
duration = models.IntegerField(default= 0, editable= False)

class Phase(models.Model):
title = models.CharField(max_length= 20)

class ProjectPhase(models.Model):
project = models.ForeignKey(Project, on_delete= models.CASCADE, related_name= 'phase')
phase = models.ForeignKey(Phase, on_delete=models.CASCADE, related_name= 'project')
start_date = models.DateField(default= timezone.now)
end_date = models.DateField(default= timezone.now)
duration = models.IntegerField(default= 0, editable= True)

最佳答案

1.在ModelAdmin中为Generaldata导入一个js媒体文件:

class YourModelAdmin(admin.ModelAdmin):    
form = YourModelForm
#list_display = ['your fields',]
class Media:
js = ("yourapp/selectajax.js",)

admin.site.register(YourModel, YourModelAdmin)

2. 创建一个新的 js 文件,保存 yourproject/yourapp/static/yourapp/目录或其他适当的目录。
jQuery(function($){
$(document).ready(function(){
$("#id_project_select").change(function(){
// console.log(obj.currentTarget.value);
$.ajax({
url:"/get_phases/",
type:"POST",
data:{project: $(this).val(),},
success: function(result) {
console.log(result);
cols = document.getElementById("id_phase_select");
cols.options.length = 0;
for(var k in result){
cols.options.add(new Option(k, result[k]));
}
},
error: function(e){
console.error(JSON.stringify(e));
},
});
});
});
});

3.创建处理ajax的 View
@login_required
def get_phases(request):
project = request.POST.get('project')
phases = {}
try:
if project:
prophases = Project.objects.get(pk=int(project)).phase
phases = {pp.phase.title:pp.pk for pp in prophases}
except:
pass
return JsonResponse(data=phases, safe=False)

4. 将 'get_phases/添加到 urlpatterns。

请注意,您应该根据需要修改一些代码。

关于javascript - Django admin 中的自定义相关下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61571330/

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