How can I create my own cleanup method for the admin site?

I want to fill in the field before checking 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)

Ultimately, I want to generate this whole "code" field, but I still get an error in admin that the field is empty, although I can see its value ("dadad") in the shell.

I also tried

def clean_code(self):

and did not call this function at all.

and i also tried

def save_model(request,....):

in the AdAdmin class, but it also did not call this.

so what should i do?

+5
source share
1 answer

, clean, Django . , . . Django .

, __init__ 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

, clean_code , .

+2

All Articles