I'm resorting to code in __init__ to set my select dropdown properly when 
using a ModelForm with formset_factory, and wondering if there is a better 
way.

I have a model that looks like this:

class Choice(models.Model):
    desc = models.TextField()
    begin_scene = models.ForeignKey(Scene, related_name='begin_scene')
    end_scene = models.ForeignKey(Scene, related_name='end_scene')

with a corresponding ModelForm.

My view contains this:

    choice_vals = scene.begin_scene.all().values()
    ChoiceFormFactory = formset_factory(ChoiceForm)
    formset = ChoiceFormFactory(initial=choice_vals)


When I render the form, I get a select dropdown which contains correct FK 
values from Scene. However, the correct option in the dropdown is not 
selected.

I did a bunch of searching and playing around and ended up with this in my 
form class, which does work to set the selected option correctly.

class ChoiceForm(ModelForm):
    def __init__(self, *args, **kwargs):
        if 'initial' in kwargs and 'end_scene_id' in kwargs['initial']:
            kwargs['initial']['end_scene'] = 
kwargs['initial']['end_scene_id']
        super(ChoiceForm, self).__init__(*args, **kwargs)

But I'm wondering if I missed something simpler/cleaner/more idiomatic. Did 
I?


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to