Question

So I have a form where I defined a select widget like this:

class AdHocVoucherTemplateForm(ModelForm):
    class Meta:
        model = AdHocVoucherTemplate
        widgets = {
            'retailer_id': Select(choices=[(r.pk, r.name) for r in Retailer.objects.all()]),
        }

This way I achieve a select input field with all retailers. User can select a retailer from a drop down list and submit the form.

The problem I noticed is that when I add a new retailer (Retailer.objects.create etc), it doesn't appear in the form in the drop down list. It appears to be cached. When I restart the uwsgi service running Django, it is there.

How can I make the widget always refresh the newest values from the database?

Was it helpful?

Solution

I don't see this caching behavior when I do something similar with a ModelChoiceField. It's default widget is a Select.

Something like:

retailer = forms.ModelChoiceField(queryset=Retailer.objects.all())

When your code is evaluated, that choices parameter is constructed once and then your select just has a static list of retailer (id,name) tuples. When the ModelChoiceField is constructed, it is referencing a QuerySet which is not evaluated until the list of choices is actually requested/displayed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top