I have a form that is collecting data from a model. The problem is if I update information in the model/DB it will not show in the form until the server is restarted.
forms.py
class RecordForm(forms.Form):
name = forms.CharField(max_length=255)
type_choices = []
choices = Domain.objects.all()
for choice in choices:
type_choices.append( (choice.id, choice.name) )
domain = forms.TypedChoiceField(choices=type_choices)
type = forms.TypedChoiceField(choices=Record.type_choices)
content = forms.CharField()
ttl = forms.CharField()
comment = forms.CharField()
I am pulling data from the Domain model. On the website I have a page to enter the Domain information. Then there is another page where it will list those domains in a drop box. However, if you add or delete anything it will not show in the dropbox until you restart the server. My guess is that django only calls the form class once. Is there a way to make sure it reruns the class code when creating a variable?
class RecordForm(forms.Form):
name = forms.CharField(max_length=255)
domain = forms.TypedChoiceField(choices=[])
type = forms.TypedChoiceField(choices=...)
content = forms.CharField()
ttl = forms.CharField()
comment = forms.CharField()
def __init__(self, *args, **kwargs):
super(RecordForm, self).__init__(*args, **kwargs)
self.fields['type'].choices = [(c.id, c.name) for c in Domain.objects.all()]
You need to get the Domain
objects each time you instantiate a RecordForm
by doing an override of the __init__
for the model form.
class RecordForm(forms.Form):
def __init__(self, *args, **kwargs):
super(RecordForm, self).__init__(*args, **kwargs)
self.type_choices = [(choice.id, choice.name,) for choice in \
Domain.objects.all()]
domain = forms.TypedChoiceField(choices=self.type_choices)
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With