trouselife
trouselife

Reputation: 969

Django Modelform - it is not validating, why?

I have a Django modelForm which I am trying to validate. The field is a 'custom' field - i.e it is not a field in the model, rather a combination of two fields that I want to parse and check if exists during cleaning. However the is_valid() form method is not working, it is saying valid=unknown when I print the form.

I am using Django crispy forms

Forms.py

class SingleSampleForm(forms.ModelForm):

    sample_id = forms.CharField(
        required=True,
        label='Sample ID:')

    class Meta:
        model = Sample
        fields = ('sample_id',)


    def __init__(self, *args, **kwargs):
        super(SingleSampleForm, self).__init__()

        self.helper = FormHelper()
        self.helper.layout = Layout(

            Field('sample_id',
                # autocomplete='off',
                css_class="search-form-label",
                ),

            Submit('submit', 'Search sample', css_class='upload-btn')
        )
        self.helper.form_method = 'POST'



    def clean_sample_id(self):

        self.sample_id = self.cleaned_data['sample_id']
        print('CLEAN SAMPLE')

        try:
            ... parse self.sample_id and check if exists ...

        except Exception as e:
            return('Sample does not exist')

Views.py:

class SampleView(View):

    sample_form = SingleSampleForm

    def get(self, request, *args, **kwargs):

        sample_form = self.sample_form()
        self.context = {
                'sample_form': sample_form,
            }

        return render(request,
                    'results/single_sample_search.html',
                    self.context)


    def post(self, request, *args, **kwargs):

        sample_form = self.sample_form(request.POST)

        if sample_form.is_valid():
            print('VALID')
            ... HttpRedirect()...

        else:
            print('NOT VALID')
            ... raise error ...

        self.context = {
                'sample_form': sample_form,
            }

        return render(request,
                    'results/single_sample_search.html',
                    self.context)

every time I submit the form charfield and try to validate it, it prints 'NOT VALID' and if i print the form it says valid=unknown. This is (almost) exactly the same as another form I have which allows me to clean the fields and validate it, even though they are not specifically Model fields. Why is the form not validating?

Thanks

Upvotes: 0

Views: 1391

Answers (1)

SHIVAM JINDAL
SHIVAM JINDAL

Reputation: 2984

Your clean_sample_id function does not returning anything but it should either return the cleaned value or raise an exception. You can refer below code to check validation.

def clean_sample_id(self):

    sample_id = self.cleaned_data['sample_id']
    if sample_id:
        return sample_id
    raise ValidationError('This field is required')

Refer for full documentation. https://docs.djangoproject.com/en/2.0/ref/forms/validation/

Upvotes: 1

Related Questions