0

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 (?)

1

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Seems what I searched. I want to get different code for each saved field, so how can I get one field in save_model-function? Like if I have fields keyX and keyY.
obj.keyX or form.cleaned_data['keyX'], it depends on what you need.
1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.