简体   繁体   中英

Saving model fields in admin interface in Django

My problem is with editing model fields in admin interface. The model has encrypted keys and I have already done a form for a user who has logged in can edit their model/keys in the website.

Now, I want to have admin be possible to edit these same keys too in the admin interface. This requires that the keys has to be encrypted first before saving them in the database.

I have my model in admin interface with code in admin.py:

admin.site.register(CryptedKeysModel)

I get shown a encrypted fields now, but if I edit any field, it isn't encrypted. I do the encryption in the views when it's showed for user in website, but where I should do the encryption, when I'm saving fields in admin interface? I guess in the models.py (?)

You can override ModelAdmin.save_model()

class SomeModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        #Encript fields values
        super(SomeModelAdmin, self).save_model(request, obj, form, change)

Sometimes it's nice to be able to add custom code to the save method of objects in the Django Admin. So, when editing an object on the Admin object detail page (change form), adding the following method override to your ModelAdmin in admin.py will allow you to add custom code to the save function.

In admin.py:

class MyModelAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        # custom stuff here
        obj.save()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM