为了账号安全,请及时绑定邮箱和手机立即绑定

将kwargs传递到Django中的自定义字段

将kwargs传递到Django中的自定义字段

一只甜甜圈 2021-04-30 09:10:30
我以这个问题作为创建自定义字段的基础:Django文件上传大小限制当我尝试进行迁移时,我收到一条错误消息,指出“ content_types”不在垃圾堆中。我已经调试了代码,几乎好像我的自定义字段init被调用了两次。一次是在我拥有此字段的模型中(带有kwarg),一次是不包含kwargs。我引用了这篇文章: 如何在Django Rest Framework的自定义字段中传递其他关键字参数?但是,无论解决方案怎么说,我已经在做。class MediaField(FileField):    def __init__(self, *args, **kwargs):        self.content_types = kwargs.pop('content_types')        self.max_upload_size = kwargs.pop('max_upload_size')        super(MediaField, self).__init__(*args, **kwargs)模型中的活动字段:media = MediaField(upload_to='media',  # this will create a folder in MEDIA_ROOT                   content_types=['jpeg', 'jpg', 'png'],                   max_upload_size=5242880)错误: KeyError: 'content_types'stacktrace:    (efs-cP0vQdei) user@right:~/Documents/websites/efs$ ./manage.py makemigrationsTraceback (most recent call last):  File "./manage.py", line 15, in <module>    execute_from_command_line(sys.argv)  File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line    utility.execute()  File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute    self.fetch_command(subcommand).run_from_argv(self.argv)  File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv    self.execute(*args, **cmd_options)  File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute    output = self.handle(*args, **options)  File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 133, in handle    ProjectState.from_apps(apps),  File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/db/migrations/state.py", line 222, in from_apps    model_state = ModelState.from_model(model)
查看完整描述

1 回答

?
www说

TA贡献1775条经验 获得超8个赞

我想出了解决方案:


在自定义字段类中添加一个解构函数:


def deconstruct(self):

    name, path, args, kwargs = super(MediaField, self).deconstruct()


    kwargs['content_types'] = self.content_types

    kwargs['max_upload_size'] = self.max_upload_size


    return name, path, args, kwargs


查看完整回答
反对 回复 2021-05-11
  • 1 回答
  • 0 关注
  • 181 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信