Gexas
Gexas

Reputation: 678

Form receives old data from model

I have form which should receive it initial value from the latest entry stored in models. However if I edit or delete model data through admin panel, initial data displayed in the form remains the same old one (despite the fact that it is deleted in models). I am baffled what I am doing wrong. At first I thought that its Chrome who saves old data, but it remains the same after resting it with ctr+shift+r.

My forms.py:

from stv.models import BazineKaina,

class DrgSkaiciuokle(forms.Form):
    bazine_kaina = forms.DecimalField(max_digits=5, decimal_places=2, required=True,
                                      label="Įveskite bazinę kainą:",
                                      initial= BazineKaina.objects.latest('data'),
                                      )


    def clean_bazine_kaina(self):
        bazine_kaina = self.cleaned_data['bazine_kaina']
        return bazine_kaina

My models.py:

class BazineKaina(models.Model):

    bazka = models.DecimalField(max_digits=5, decimal_places=2)

    data = models.DateField(auto_now=False, auto_now_add=True)

    def __str__(self):
        return str(self.bazka)

    class Meta:
        verbose_name_plural = "Bazinė kaina"
        get_latest_by = 'data'

Please help me to find out why old data is still received by form?

EDIT: I found out, that if I restart the server data will be refreshed, but that cant be solution in production. How to make form get new data every time its called?

Upvotes: 1

Views: 49

Answers (2)

Gexas
Gexas

Reputation: 678

Based on dirkgroten advice and this source I found complete solution:

forms.py:

class DrgSkaiciuokle(forms.Form):

    bazine_kaina = forms.DecimalField(max_digits=5, decimal_places=2, required=True,
                                      label="Įveskite bazinę kainą:",
                                      help_text="Įprastiniams skaičiavimams naudokite einamųjų metų bazinę kainą",
                                      error_messages={'max_digits': 'Bazinė kaina neturi viršyti 5 skaitmenų.'},
                                      )

    def __init__(self, *args, **kwargs):
        initial_arguments = kwargs.get('initial', None)
        updated_initial = {}
        updated_initial['bazine_kaina'] = BazineKaina.objects.latest('data')
        kwargs.update(initial=updated_initial)
        super(DrgSkaiciuokle, self).__init__(*args, **kwargs)


    def clean_bazine_kaina(self):
        bazine_kaina = self.cleaned_data['bazine_kaina']
        return bazine_kaina

Upvotes: 0

dirkgroten
dirkgroten

Reputation: 20702

Your DrgSkaiciuokle is imported when Django starts and any class attributes are instantiated then. So the query to .latest() is performed once when you runserver or start your Django workers and initial will not change anymore.

Set initial in the form's __init__ method so it gets called each time the form is instantiated.

Upvotes: 3

Related Questions