[Answered ]-How to POST with a field which is not specified in Form's Meta fields?

2👍

Jason. An alternative would be to include the field you want in the form’s Meta class and alter the queryset in the form’s __init__ method.

class DataCorrectForm(forms.ModelForm):
    reference = forms.IntegerField()
    def clean(self):
        cleaned_data = super(DataCorrectForm, self).clean()
        cleaned_data['referenceData'] = DataNeedsCorrection.objects.get(data_id=cleaned_data['reference']) 
        # I extract a record that matches data_id and assign it to the form data
        return cleaned_data


    def save(self, commit=True):
        return super(DataCorrectForm, self).save(commit=commit)


    class Meta:
        model = DataCorrected
        fields = [
            'reference',
            'referenceData',
            'correctedText',
        ]

    def __init__(self, *args, **kwargs):
        super(DataCorrectForm, self).__init__(*args, **kwargs)
        self.field['referenceData'].queryset = DataNeedsCorrection.objects.none()

If this doesn’t match what you’re looking for let me know(so I can delete it or provide another solution).

Additional changes I would suggest:

  • You’re overriding the save method in the form but not doing anything new. I’d remove that.

  • Remove the_form.clean(). This happens in form.is_valid()

  • I’m not sure what the IndexView is, but if it inherits from the FormView, your whole entire post method is unnecessary.

  • Django already provides a primary key, so you don’t need to add the AutoFields

Leave a comment