Repopulate Django ChoiceField without restarting the server

advertisements

I have a simple form where users can select a department from a choicefield.

This is my form :

class NewDealForm1(forms.Form):
        department = forms.ChoiceField(choices = map(lambda x:('%s'% x.id, '%s' % x.title),Department.objects.all()))

Whenever I add a new department from admin, my choicefield doesn't display new department unless I restart my server.

How can i display all departments without restarting the server ?


Instead of using a forms.ChoiceField you should try a forms.ModelChoiceField which takes a queryset directly.

Docs: https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield

Example

class NewDealForm1(forms.Form):
    department = forms.ModelChoiceField(queryset=Department.objects.all()))