[Answered ]-Django: How to custom save a model/form based on a non-persistent field of a form?

2👍

Override the save_model() method of the EntryAdmin:

class EntryAdmin(MarkdownModelAdmin):
    ...
    def save_model(self, request, obj, form, change):
        if form.cleaned_data.get('to_publish'):
            obj.publication_date = datetime.now()
        obj.save()

The other (and more complex) option is to override the EntryAdminForm.save() method:

class EntryAdminForm(forms.ModelForm):
    ....
    def save(self, *args, **kwargs):
        entry = super(EntryAdminForm, self).save(*args, **kwargs)
        if self.cleaned_data.get('to_publish'):
            entry.publication_date = datetime.now()
            if kwargs.get('commit', True):
                entry.save()
        return entry

Leave a comment