On Sunday, 8 July 2012 04:25:54 UTC+1, Lee Hinde wrote:
>
> I have a table, Choice, that is used to build common lists. For 
> instance, there might be a list "Employment_Status" with values 
> "Full-Time" and "Part-Time" 
>
> I want to use those values in various forms, so in the appropriate 
> models.py I have: 
>
> def _get_list_choices(list): 
>     choices = Choice.on_site.filter(category = 
> list).values_list('choice', flat=True).order_by('sort_order') 
>     return  tuple(choices) 
>
>
> and then I'd use it like this: 
>
> class PersonForm(ModelForm): 
>     household = forms.CharField( 
>                   widget=forms.HiddenInput()) 
>     employment_types = _get_list_choices('Employment_Status') 
>     employment_status = ChoiceField(widget=forms.Select, choices = 
> zip(employment_types,employment_types)) 
>
>
> What I'm noticing is that (in dev mode) the choice list for 
> 'employment_status' doesn't update unless I trigger a change, either 
> to the forms.py or restart the dev server. 
>
> I'm wondering if there's a better place to handle this. 
>
> Thanks. 
>


The problem, as you've probably guessed, is that the _get_list_choices() 
function is called when the form is defined, which happens when its module 
is first imported during a process. The choices are allocated at that 
point, and don't change while the process lasts.

So instead you need to make sure the function is called every time the form 
is instantiated, which you can do in the __init__ method:

    class MyForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super(MyForm, self).__init__(*args, **kwargs)
            self.fields['employment_status'].choices 
= _get_list_choices('Employment_Status') 

Alternatively, you might want to consider using a ModelChoiceField instead 
of a plain ChoiceField, and using the `queryset` parameter rather than 
`choices` - your method can then return the actual Choice objects, and the 
field will ensure that the queryset is evaluated each time.
--
DR. 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/thKzfxBwT4MJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to