在Django中,有一种明智的方法可以将表单进行序列化吗?

3

我正在尝试在Django中pickle一个表单。这样我就可以从另一个网页调用同一点。然而,我遇到了一个错误:

_pickle.PicklingError: Can't pickle <function paginator_number at 0x0000020BD0CBE840>: it's not the same object as django.contrib.admin.templatetags.admin_list.paginator_number

由于pickle无法处理函数。是否有更好的解决方法或替代方案?我想知道将表单pickle化是否只是一种不好的做法。

1个回答

0
当我需要缓存和恢复表单状态时,我遇到了相同的问题。问题出在表单的renderer属性和它的一些属性上,比如form._errors(详见表单渲染API)。
我的解决方法是为django.forms.renderers.DjangoTemplates渲染器注册一个自定义的pickle处理程序,这样在pickle时它不会保存任何状态。在反pickle时,对象会从头开始重新创建。
import copyreg

from django.forms.renderers import DjangoTemplates

def pickle_django_templates(instance):
    return DjangoTemplates, ()


copyreg.pickle(DjangoTemplates, pickle_django_templates)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接