first post here! I am trying to pre-select an option in a filter-horizontal I added to the change_form of my model. The id of the option to pre-select is in the url. How would I go to retrieve it in the init method of my form?
I saw this link, retrieve url in init, but considering that the form is instantiated automatically by the admin, it does not seem to fit the bill. (Unless I'm missing something?)
Here's my code.
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
Is there an easy way to do this?
I managed to do what I wanted via jQuery, but I would like to know if there is a way to do it in the init method…
edit: Here's my current JS snippet, just in case it could be of use to someone… Basic jquery, but anyway…
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')