Django: How to change the value of a form field before rendering it, but after the form has been initialized?

Given the form, I want to change the value in the field before rendering it. This is what I am trying:

class RequiredFormSet(BaseFormSet): def add_form(self): tfc = self.total_form_count() self.forms.append(self._construct_form(tfc)) if self.is_bound: data = self.management_form.data.copy() # make data mutable data[TOTAL_FORM_COUNT] = self.management_form.cleaned_data[TOTAL_FORM_COUNT] + 1 self.management_form.data = data else: self.extra += 1 

I thought everything was stored in data , but I assume that data has already been passed to individual fields (or widgets)? So which property do I need to change exactly?

+4
source share
1 answer

Hope this helps:

This is the method that creates the forms in BaseFormSet:

 def _construct_form(self, i, **kwargs): """ Instantiates and returns the i-th form instance in a formset. """ defaults = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)} if self.is_bound: defaults['data'] = self.data defaults['files'] = self.files if self.initial: try: defaults['initial'] = self.initial[i] except IndexError: pass # Allow extra forms to be empty. if i >= self.initial_form_count(): defaults['empty_permitted'] = True defaults.update(kwargs) form = self.form(**defaults) self.add_fields(form, i) return form 

As you can see there is an attribute called "self.initial", it is passed as input to the newly created form. If you want to use _construct_form to add a new form and set custom source data, you must change "self.initial" before calling _construct_form. The initial one should be a dictionary, where the key is the name of the field and the value you want for your field.

+1
source

Source: https://habr.com/ru/post/1339273/


All Articles