Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I create a custom clean method for admin site?

I want to populate a field before validation in admin.

models.py

class Ad(models.Model):
    .....
    manual_code  = models.BooleanField("Manual Code", default=False)
    code          = models.TextField("Code")

admin.py

class MyAdAdminForm(forms.ModelForm):
    class Meta:
        model = Ad

    def clean(self):
        cleaned_data = self.cleaned_data
        cleaned_data['code'] = "dadad"
        print cleaned_data
        return cleaned_data

class AdAdmin(admin.ModelAdmin):
    form = MyAdAdminForm

admin.site.register(Ad, AdAdmin)

eventually I wanna generate that whole "code" field, but I'm still getting the error in admin that the field is empty although I can see the value of it ("dadad") in the shell.

I also tried

def clean_code(self):

and it wasn't calling that function at all.

and I also tried

def save_model(request,....):

in the AdAdmin class but it wasn't calling that either.

so what should I do?

like image 892
dado_eyad Avatar asked Nov 04 '22 23:11

dado_eyad


1 Answers

As well as calling your custom clean method, Django validates each form field individually. It is the individual field check that is causing the required field error. For full details see the Django docs on Form and field validation.

If you do not require user input in the code field, you can override the form's __init__ method, and set required=False.

class MyAdAdminForm(forms.ModelForm):
    class Meta:
        model = Ad

    def __init__(self, *args, **kwargs):
        super(MyAdAdminForm, self).__init__(*args, **kwargs)
        self.fields['code'].required = False

Once the field is not required, the form will call the clean_code method during validation, so you can set the value there.

like image 75
Alasdair Avatar answered Nov 09 '22 09:11

Alasdair