即使我传递了参数,也在kwargs.pop中获取KeyError

时间:2017-12-15 13:22:59

标签: python keyerror kwargs

我有以下代码

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models

from .validators import audio_validator

# Create your models here.

from django.forms import forms
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _

MAX_FILE_SIZE=20971520

UPLOAD_TO = 'uploads'

class ContentTypeRestrictedFileField(models.FileField):

    def __init__(self, *args, **kwargs):
        self.content_types = kwargs.pop("content_types")
        self.max_upload_size = kwargs.pop("max_upload_size")

        super(ContentTypeRestrictedFileField, self).__init__(*args, **kwargs)

    def clean(self, *args, **kwargs):
        data = super(ContentTypeRestrictedFileField, self).clean(*args, **kwargs)

        file = data.file
        try:
            content_type = file.content_type
            if content_type in self.content_types:
                if file._size > self.max_upload_size:
                    raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(self.max_upload_size), filesizeformat(file._size)))
            else:
                raise forms.ValidationError(_('Filetype not supported.'))
        except AttributeError:
            pass

        return data

class AudioFile(models.Model):
    file_name = models.CharField(max_length=100)
    audio_file = ContentTypeRestrictedFileField(upload_to=UPLOAD_TO, validators=[audio_validator], content_types=['audio/aac', 'audio/mpeg', 'audio/ogg', 'audio/x-wav', 'audio/webm', 'audio/3gpp',], max_upload_size=MAX_FILE_SIZE)
    uploaded_at = models.DateTimeField(auto_now_add=True)

正如您所看到的,我将content_types作为列表传递,但它无效。 当我运行`./manage.py migrate时,我得到了

raceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/student/PycharmProjects/nightenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/home/student/PycharmProjects/nightenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/student/PycharmProjects/nightenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/student/PycharmProjects/nightenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/home/student/PycharmProjects/nightenv/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 184, in handle
    ProjectState.from_apps(apps),
  File "/home/student/PycharmProjects/nightenv/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 230, in from_apps
    model_state = ModelState.from_model(model)
  File "/home/student/PycharmProjects/nightenv/local/lib/python2.7/site-packages/django/db/migrations/state.py", line 432, in from_model
    fields.append((name, field.clone()))
  File "/home/student/PycharmProjects/nightenv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 469, in clone
    return self.__class__(*args, **kwargs)
  File "/home/student/PycharmProjects/tonightcore/nightcore/models.py", line 34, in __init__
    self.content_types = kwargs.pop("content_types")
KeyError: u'content_types'

如果我print(kwargs)我明白了:

{'content_types': [u'audio/aac', u'audio/mpeg', u'audio/ogg', u'audio/x-wav', u'audio/webm', u'audio/3gpp'], 'max_upload_size': 20971520, 'upload_to': u'uploads', 'validators': [<django.core.validators.FileExtensionValidator object at 0x7fb90952a9d0>]}
{'upload_to': u'uploads', 'validators': [<django.core.validators.FileExtensionValidator object at 0x7fb909441090>]}

在例外之前。

3 个答案:

答案 0 :(得分:2)

阅读有关pop工作原理的文档:

In [65]: dict.pop?
Docstring:
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
Type:      method_descriptor

现在查看你的堆栈跟踪。看起来django试图以某种方式实例化对象而不传递必需的keyword-args。所以最好只添加一个默认值pop

答案 1 :(得分:0)

看来Django实际上在没有ContentTypeRestrictedFileField我没有通过kwargs的情况下调用print(kwargs)

如果我kwargs.pop按照某些用户的建议,我发现这些自定义参数不存在。

也许Django对所有ModelFileds都这样做。

我为def __init__(self, *args, **kwargs): print(kwargs) self.content_types = kwargs.pop("content_types", []) self.max_upload_size = kwargs.pop("max_upload_size", 5242880) 添加了默认参数,现在可以使用了。甚至文件验证都可以。

我甚至通过删除Django的默认文件扩展名验证器来测试。

struct GenericStruct<T>

答案 2 :(得分:0)

您可以轻松地将默认参数添加到self_variables(self.content_typesself.max_upload_size),如此...

def __init__(self, *args, **kwargs):
    self.content_types = kwargs.pop("content_types", [])
    self.max_upload_size = kwargs.pop("max_upload_size", [])