Answering my own question from a few days ago, this:

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

is all wrong. I needed to be using a modelformset_factory, not a
formset_factory, with a few extra params:

    ChoiceFormSetFactory = modelformset_factory(Choice, form=ChoiceForm,
extra=0)
    formset = ChoiceFormSetFactory(queryset=scene.begin_scene.all())

This assigns the value of the select widget correctly out of the box, and
also avoids some later issues I ran into with .values() and initial=.

Matt







On Mon, May 6, 2013 at 4:28 PM, Matt C <[email protected]> wrote:

> 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 [email protected].
> To post to this group, send email to [email protected].
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

-- 
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 [email protected].
To post to this group, send email to [email protected].
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