0

I'm sending an optional value through a url to a generic view which uses a Modelform like so:

class myClass(generic.CreateView):
   template_name = 'template.html'
   form_class = myForm
   ...

The modelform is something like:

class myForm(ModelForm):
    institution = CustomModelChoiceField(...)
    class Meta:
       model = myModel
       ...

I need to set the default selected value in the dropdown field to the value passed in the url.

The value being passed is the 'id' of the model.

  1. How would I pass the value to myForm?
  2. How would myForm set it as the 'selected' value?

I'm open to other ways to doing this.

The bigger picture:

I have a form1(model 1) where I popup another form2(model2)(foreign key to model 1). On success of form2, form1 dropdown sets to the new foreigh key.

I've thought about doing it through AJAX, but for future features, it would be a good idea to pass the value in the url.

Again, open to other ways.

Thanks.

Ryan
  • 269
  • 1
  • 3
  • 15

1 Answers1

1

If I understand correctly, you can override a get_form_kwargs method to pass id into the form constructor (see this)

# views.py

def get_form_kwargs(self):
    kwargs = super(CreateView, self).get_form_kwargs()
    kwargs.update({'id': self.kwargs.get('id')})
    return kwargs

# forms.py

def __init__(self, *args, **kwargs):
    id = kwargs.pop('id', None)
    super(Form, self).__init__(*args, **kwargs)
    self.fields['id'].initial = id 
erthalion
  • 3,094
  • 2
  • 21
  • 28
  • doesn't work, i get the following error: __init__() got an unexpected keyword argument 'id' – Ryan Mar 06 '14 at 13:01
  • I figured out what was wrong, and I edited your answer, you probably can't see it yet. Essentially, the kwargs had to be returned to their original form, so: my_arg_val = kwargs.pop('id', None) was needed before 'super' in '__init__' was called. – Ryan Mar 06 '14 at 13:21
  • @Ryan Yes, it's the my inattention, sorry =) – erthalion Mar 06 '14 at 13:47