1

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')
Community
  • 1
  • 1
phenxd
  • 689
  • 4
  • 17
  • Another way - use thread locals to get request, but http://stackoverflow.com/questions/3227180/why-is-using-thread-locals-in-django-bad – vadimchin Feb 04 '14 at 03:26
  • Thanks, this is something I did not know about. Not sure I wanna go down that road though... – phenxd Feb 05 '14 at 04:41

1 Answers1

1

Well, searching for something different, I fell upon this great answer by Chris Pratt which is exactly what I was looking for at the time.

Turns out that 'request' is accessible through kwargs...

Leaving this here as an answer anyway...

Community
  • 1
  • 1
phenxd
  • 689
  • 4
  • 17