The correct way of modifying data before saving a model via the admin site

Django 4.1

models.py

class Video(models.Model):
    phrase_id = models.IntegerField(default=-1,
                                    blank=False,
                                    null=False,
                                    validators=[MinValueValidator(0)])

    # This field will be read only in the admin site.
    # Its only purpose is to ensure cascade deletion.
    _phrase = models.ForeignKey("vocabulary_phrases.Phrase",
                                on_delete=models.CASCADE,
                                default="",
                                blank=True,
                                null=True)

admin.py

class VideoAdmin(admin.ModelAdmin):
    list_display = ["phrase_id", "name", ]
    list_filter = ['phrase_id']
    readonly_fields = ('_phrase',)
    form = VideoForm
admin.site.register(Video, VideoAdmin)

forms.py

class VideoForm(ModelForm):


    def clean(self):
        if ("phrase_id" in self.changed_data) and self.cleaned_data.get("phrase_id"):
            phrase_id = self.cleaned_data["phrase_id"]
            _phrase = _get_phrase(phrase_id)
            self.cleaned_data["_phrase"] = _phrase
        return self.cleaned_data


    class Meta:
        model = Video
        exclude = []

In the admin site a user inserts an integer for phrase_id. Then in the admin form I wanted to substitute self.cleaned_data with Phrase instance I extract from the database.

Well, the problem is that after saving, _phrase field is empty.

Thid is the documentation: https://docs.djangoproject.com/en/4.1/ref/forms/validation/

It reads as follows:

The form subclass’s clean() method... This method can return a completely different dictionary if it wishes, which will be used as the cleaned_data

Well, I have modified the cleaned_data, but it seems to have no effect on what is saved. My idea was: data are validated before saving, substitute cleaned_data, then your own data will be saved. I seem to have been wrong.

Could you help me understand the correct way of modifying data before saving a model via the admin site.

Back to Top