gintas / django-picklefield

A pickled object field for Django
MIT License
180 stars 47 forks source link

Make admin editable widget a TextArea #45

Open BarnabasSzabolcs opened 5 years ago

BarnabasSzabolcs commented 5 years ago

I edit PickledObjectField's in admin using editable=True flag where the assigned widget is a textbox. So I have to add the following line to my admin class: formfield_overrides = {PickledObjectField: {'widget': widgets.AdminTextareaWidget}, } I think it'd be nice if this was the default behaviour.

BarnabasSzabolcs commented 5 years ago

No, sorry, now I see that the issue is more complex - before saving a PickledObjectField view the admin, we need to run json.loads() on it... duh

BarnabasSzabolcs commented 5 years ago

Ok, so my solution so far:

import ast
from django.contrib.admin import widgets
from picklefield.fields import dbsafe_encode

class PickledObjectFieldAdminTextAreaWidget(widgets.AdminTextareaWidget):
    def value_from_datadict(self, data, files, name):
        value = data.get(name)
        # we gotta have a PickledObject here otherwise CharField cleaning kicks in
        return dbsafe_encode(ast.literal_eval(value), False, 2, True)

and

class MyAdmin(admin.ModelAdmin):
    formfield_overrides = { PickledObjectField: {'widget': PickledObjectFieldAdminTextAreaWidget},}