简体   繁体   中英

Django self.cleaned_data problems.

Have a fully working form created in Django - however it breaks when I try to define a function to raise custom form.ValidationError .

 # importing form modules

from django import forms
import re

# define the forms

class single_input(forms.Form):

    CHROMOSOMES = (

                    ('1'  ,  '1'),
                    ('2'  ,  '2'),
                    ('3'  ,  '3'),
                    ('4'  ,  '4'),
                    ('5'  ,  '5'),
                    ('6'  ,  '6'),
                    ('7'  ,  '7'),
                    ('8'  ,  '8'),
                    ('9'  ,  '9'),
                    ('10' ,  '10'),
                    ('11' ,  '11'),
                    ('12' ,  '12'),
                    ('13' ,  '13'),
                    ('14' ,  '14'),
                    ('15' ,  '15'),
                    ('16' ,  '16'),
                    ('17' ,  '17'),
                    ('18' ,  '18'),
                    ('19' ,  '19'),
                    ('20' ,  '20'),
                    ('21' ,  '21'),
                    ('22' ,  '22'),
                    ('23' ,  '23'),
                    ('X'  ,  'X'),
                    ('Y ' ,  'Y')

                    ) 

    def clean_testname(self):

        print self.cleaned_data

        testname      = self.cleaned_data['testname']   
        genome_pos    = self.cleaned_data['genome_pos']


        if ( not re.match(r"^\w+$", testname)):

            raise forms.ValidationError(

                "Test name is only allowed letter's number's and _'s ."
                "NO spaces or funny things that involve the shift button"  
                )

        if ( not re.match(r"^\s+$", genome_pos)):

            raise forms.ValidationError(

                "Genome position is only allowed numbers and -'s"
                "NO spaces, letter or funny things that involve the shift button"

                ) 


        return cleaned_data


    testname   = forms.CharField ( label='testname', max_length=100 )
    chromosome = forms.ChoiceField( label='chromosome', choices = CHROMOSOMES , required = True)
    genome_pos = forms.CharField ( label='genome_pos', max_length=15 )

The problem is it only takes the first form field into cleaned_data so a print cleaned_data from the above code looks like:

{'testname': u'ssss'}

Wheras if I comment out the entire clean_testname function I get a working output

{'genome_pos': u'xxx', 'testname': "name", 'chromosome': u'1'}

The problem is that you are trying to clean the testname and genome_pos fields in the clean_testname method.

You should clean the testname field in the clean_testname method, and the genome_pos field in the clean_genome_pos methods.

If you want to validate fields that depend on each other , then this belongs in the clean method. In this case, it doesn't look like you need a clean method, because the field names do not appear to depend on each other.

class SingleInput(forms.Form):
    # It would be better to name the form SingleInput rather than single_input

    def clean_testname(self):
        test_name = self.cleaned_data['testname']
        # validate testname, raise ValidationError if necessary.
        # you can't access any other fields from self.cleaned_data here
        return testname

    def clean_genome_pos(self):
        test_name = self.cleaned_data['genome_pos']
        # validate genome_pos, raise ValidationError if necessary.
        # you can't access any other fields from self.cleaned_data here
        return genom_post

    def clean(self):
        cleaned_data = super(SingleInput, self).clean()

        # you need to handle case when the fields do not exist in cleaned_data
        testname = cleaned_data.get('testname')   
        genome_pos = cleaned_data.get('genome_pos')

        if testname and genome_pos:
            # do any checks that rely on testname *and* genome_pos, and
            # raise validation errors if necessary
            ...

        return cleaned_data

Another option in your case would be to use RegexField instead of custom clean methods.

class SingleInput(forms.Form):
    testname = forms.RegexField(
        label='testname', 
        max_length=100,
        regex=r"^\w+$",
        message="<error message>",
    )
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM