【发布时间】:2023-04-01 03:50:01
【问题描述】:
编辑: 我决定把我的问题改成这个,希望一个更笼统的问题会更有吸引力......
所以我有一个模型,它有一个 M2M 字段,它不在服务器中翻译,但在客户端。我可以在 admin-ui 中对这个字段进行排序吗,尤其是每次添加模型的新实例时?
这是我最后一次尝试:
感兴趣的模型是:
class Recipe(models.Model):
name = models.CharField(max_length=200,verbose_name=_("name"))
ingredient_list = models.ManyToManyField(IngredientType, through='Ingredient')
class IngredientType(models.Model):
name = models.CharField(max_length=25)
class Ingredient(models.Model):
ingredient_type =models.ForeignKey(IngredientType,verbose_name=_("IngredientType"))
recipe = models.ForeignKey(Recipe)
recipe_admin.py:
class IngredientInline(admin.TabularInline):
model = Ingredient
extra = 1
class RecipeAdmin(admin.ModelAdmin):
inlines = [IngredientInline]
form = RecipeForm
class RecipeForm(forms.ModelForm):
class Meta:
model = Recipe
我在我的 initial_data.json 文件中添加了一长串 IngredientType 对象。 现在,每次有人在他的食谱中添加新成分时,他都会从打开的长下拉列表中选择一种成分类型。
编辑: 在浏览器中查看表单的 html 时,我的下拉列表中有这些行。 如您所见,在字段下方有一行负责使用 showAddAnotherPopup(this) 函数向内联添加另一行: (我想以某种方式挂钩该函数,并且每次调用它时,都会调用我的排序函数)
<select id="id_ingredient_set-0-ingredient_type" name="ingredient_set-0-ingredient_type">
<option value="" selected="selected">---------</option>
<option value="42">אבוקדו</option>
<option value="80">אבטיח</option>
....
</select>
<a href="/admin/vcb/ingredienttype/add/" class="add-another" id="add_id_ingredient_set-0-ingredient_type" onclick="return showAddAnotherPopup(this);"> <img src="/static/admin/img/icon_addlink.gif" width="10" height="10" alt="Add another"></a>
我的问题是,用户添加到他的食谱表单中的动态添加的成分行会导致下拉成分类型名称列表未排序。我可以按希伯来语字母顺序排序,但我只对页面加载时已经明显的行进行了排序。
我通过将 django 的 tabular.html 文件迁移到我的项目文件系统中,并添加一些对其进行排序的 js 来完成上述操作:
function sortAlpha(a,b){
return a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase() ? 1 : -1;
};
我这样称呼它:
('#id_ingredient_set-0-ingredient_type option').sort(sortAlpha).appendTo('#id_ingredient_set-0-ingredient_type');
在页面加载时触发的函数内部。 但是这种方法显然不能处理用户添加到他的食谱表单中的所有动态添加的成分行,这会导致下拉成分类型名称列表未排序。 (它与当前的 id 挂钩)
这是我也添加到项目文件系统中的 django 的 showAddAnotherPopup 方法:
function showAddAnotherPopup(triggeringLink) {
var name = triggeringLink.id.replace(/^add_/, '');
name = id_to_windowname(name);
href = triggeringLink.href
if (href.indexOf('?') == -1) {
href += '?_popup=1';
} else {
href += '&_popup=1';
}
var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
win.focus();
return false;
}
我是一个 django 菜鸟,所以我仍然缺乏所有 AJAX/js/templatetag 流行语的知识... 帮助将不胜感激。 tnx 尼赞
【问题讨论】:
-
如果缺少更多信息,我很乐意提供..
标签: python django django-forms django-templates