Django: form values ​​are not updated when updating the model

I am creating a form that uses MultipleChoiceField. The values ​​for this field are derived from another model. This method works fine, but I notice (on the production server) that when adding a new element to the model in question (NoticeType) the form does not dynamically update. I have to restart the server for a new item to be displayed on my MultipleChoiceField.

Any changes to the NoteType model (editing elements or creating new ones) do not apply to the form. After restarting the production server, updates will appear.

Any ideas why this could be? The relevant part of the form is given below. Thanks.

from django import forms from django.contrib.auth.models import User from notification.models import NoticeType class EditUserProfileForm(forms.Form): CHOICES = [] for notice in NoticeType.objects.all(): CHOICES.append( (notice.label,notice.display) ) notifications = forms.MultipleChoiceField( label="Email Notifications", required=False, choices=( CHOICES ), widget=forms.CheckboxSelectMultiple,) 
+4
source share
2 answers

My guess is that the class definition is only processed once at boot time, and not for each instance. Try adding a CHOICES calculation to the init method, for example:

 def __init__(self, *args, **kwargs): super(self.__class__, self).__init__(*args, **kwargs) CHOICES = [] for notice in NoticeType.objects.all(): CHOICES.append( (notice.label, notice.display) ) self.fields['notifications'].choices = CHOICES 
+6
source

Although mherren is correct that you can fix this problem by defining your choice in the __init__ method, there is an easier way: use ModelMultipleChoiceField , which is specifically designed to fulfill the request and is updated dynamically.

 class EditUserProfileForm(forms.Form): notifications = forms. ModelMultipleChoiceField( label="Email Notifications", required=False, queryset = NoticeType.objects.all(), widget=forms.CheckboxSelectMultiple) 
+8
source

All Articles