Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - form field will not update without server reset... instantiating a class again

Tags:

python

django

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?

like image 572
Vince Avatar asked Jan 13 '23 23:01

Vince


2 Answers

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()]
like image 150
Timmy O'Mahony Avatar answered Jan 19 '23 10:01

Timmy O'Mahony


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)
    ...
like image 37
Brandon Avatar answered Jan 19 '23 12:01

Brandon