Using clean_fields and full_clean in django Admin

519 views
Skip to first unread message

nav

unread,
Dec 4, 2012, 6:40:41 AM12/4/12
to django...@googlegroups.com
Dear Folks,

I have an Admin form which has two textfields namely country and state. I have made it more user friendly by making textfield a dropdown with the value to select for those fields.

The model i have has some constraints which I cannot change i.e. that the country value must be a 2 letters in length such as 'US' for United States as these codes are unique. Simlarly for states of a country which can have code up to 10 letters in length. Since my dropdown contains the names and not the codes I need a way to excude them from validation change there values so that they are database friendly and save them.

After much research I came across two methods full_clean() and clean_fields() which is where the key lies but I have no idea how to use them.

So far the validation errors on country and state keep firing and there does not seem a way to stop it. Secondly if you exclude fields from validation do I access them directly using the POST data and modify them before saving?

The relevant code is below:

class GroupAdminForm(forms.ModelForm):
   
    creator = CustomCreatorChoiceField(queryset=User.objects.order_by('last_name'))
    country = CustomLocationChoiceField(queryset=Country.objects.order_by('name'))
    state = CustomLocationChoiceField(queryset=Subdivision.objects.order_by('name'))
   
    def clean_fields(self, exclude=['country', 'state']): # or I could use full_clean
        print "Inside clean_fields"
        return

    def __init__(self, *args, **kwargs):
        super(GroupAdminForm, self).__init__(*args, **kwargs)
        self.fields['country'].initial = DEFAULT_COUNTRY

My model is below:

class Group(models.Model):

    # Name of the group
    name = models.CharField(max_length=100)
    # Longer description of group
    description = models.TextField(blank=True)
    # Group owner
    creator = models.ForeignKey(User, related_name='groups_created')
    # Creation date
    creation_date = models.DateTimeField()

    # Country foreign key to Country table in Geography App
    country = models.CharField(max_length=2, null=True, default='US')

    # State foreign key to State table in Geography App
    state = models.CharField(max_length=10, null=True, blank=True)

    # City where group is located
    city = models.CharField(max_length=40, null=True, blank=False)

    # Public (searchable) group
    public = models.BooleanField(default=True, null=False)

Please do let me know if anything else is needed.

Cheers,
nav

      

Chris Cogdon

unread,
Dec 4, 2012, 6:51:37 PM12/4/12
to django...@googlegroups.com
Best thing I can suggest is to create a clean_FIELDNAME method in the ModelForm... this method should use self.cleaned_data['FIELDNAME'] to retrieve the value. check it, and return it if things are good, or raise ValidationError if things are bad.

An alternate is to make the adjustment to the Model Field... when you create the country,CharField... pass a callback function through the validators attribute to validate.

This way you'll validate at the model level, rather than the form level.

nav

unread,
Dec 5, 2012, 1:58:23 AM12/5/12
to django...@googlegroups.com
Thanks. It seems so obvious something kept telling that forms worked differently in the Admin interface compared to normal developer defined forms. This is exactly what I would have done if it was form that I had defined.

Cheers,
nav
Reply all
Reply to author
Forward
0 new messages