Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change form field value before saving

I have a form:

class ReferencesForm(forms.ModelForm):

    error_css_class = 'error'   #set some css when an error
    contactName = forms.CharField(label='Contact Name:')
    company = forms.CharField(label='Company:')
    address = forms.CharField(label='Address:')
    telephoneNumber = forms.CharField(label='Telephone Number:')

    class Meta:
        fields = '__all__'
        model = References

    def __init__(self, *arg, **kwarg):
        super(ReferencesForm, self).__init__(*arg, **kwarg)
        self.empty_permitted = True
    def clean(self):
        """ Custom validation for fields
        """
        cleaned_data = super(ReferencesForm, self).clean()

        return self.cleaned_data  

And build it up in my views file like so:

ReferencesInlineFormSet = inlineformset_factory(
        Applicant, References, form=ReferencesForm, extra=1, can_delete=False)
...
if request.method == 'POST':
    references_formset = ReferencesInlineFormSet(
        request.POST, instance=applicant)

    if (references_formset.is_valid()):
        references_formset.instance['address'] = "test";
        references_formset.save();

I don't think the applicant model is important here but if necessary I can add it later.

I want to merge some address fields (addr1, addr2, town etc.) into one database field called "address" and was thinking of doing that in the views file.

I tried a simple assignment with "test" here and I received the error:

'Applicant' object does not support item assignment
references_formset.instance['address'] = "test"; 
like image 225
Jon Avatar asked Dec 09 '22 04:12

Jon


1 Answers

You could use something like this:

if form.is_valid():
    obj = form.save(commit=False)
    obj.address = "test"
    obj.save()
like image 135
nitimalh Avatar answered Mar 03 '23 20:03

nitimalh