gpt4 book ai didi

python - 从 django admin 中的 URL 中预选择水平过滤器中的选项

转载 作者:太空宇宙 更新时间:2023-11-03 18:36:15 24 4
gpt4 key购买 nike

第一篇文章在这里!我正在尝试在添加到模型的change_form 中的水平过滤器中预先选择一个选项。预选选项的 id 位于 url 中。我如何在表单的 init 方法中检索它?

我看到了这个链接,retrieve url in init ,但考虑到该表单是由管理员自动实例化的,它似乎不符合要求。 (除非我错过了什么?)

这是我的代码。

class Section(models.Model):
title = models.CharField()
groups = models.ManyToManyField('Group', related_name='sections')

class Group(models.Model):
title = models.CharField()

class GroupForm(forms.ModelForm):
//Adding a filter-horizontal to the
sections = forms.ModelMultipleChoiceField(
queryset=Section.objects.all(),
required=False,
widget=FilteredSelectMultiple(
verbose_name=('Sections'),
is_stacked=False
)
)

class Meta:
model = Group

def __init__(self, *args, **kwargs):
super(GroupForm, self).__init__(*args, **kwargs)
if self.instance.pk:
self.fields['sections'].initial = self.instance.sections.all()
else:
//How-to...
//Retrieve sectionID from URL and add to initial
self.fields['sections'].initial = …

def save(…)
//saving the selected sections

有没有简单的方法可以做到这一点?

我设法通过 jQuery 做我想做的事,但我想知道是否有办法在 init 方法中做到这一点......

编辑:这是我当前的 JS 片段,以防万一它可能对某人有用......基本的 jquery,但无论如何......

function getFromURI(URI, paramName) {
var hash;
if(paramName != undefined){
URI = URI.split('&');
for(var i = 0; i < URI.length; i++){
hash = URI[i].split('=');

if (hash[0] == paramName)
return hash[1]
}
}
return null
}

var q = document.URL.split('?')[1];
var id = getFromURI(unescape(q), 'sectionId')

$('#id_sections_from option[value="' + id + '"]').detach().appendTo('#id_sections_to')

最佳答案

好吧,在寻找不同的东西时,我发现了 this great answer by Chris Pratt这正是我当时正在寻找的东西。

事实证明,“请求”可以通过 kwargs 访问...

无论如何,将其留在这里作为答案......

关于python - 从 django admin 中的 URL 中预选择水平过滤器中的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21536221/

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