我试图在Django中创建一个允许用户链接文件或上传文件的自定义表单字段。为此,我创建了MultiValueField的子类,其fields属性设置为(URLField(),FileField())。我不确定这是正确的方法,但我一直收到一个我无法理解的错误:
'MyFileField' object has no attribute 'attrs'
这是我的代码。谁能解释一下发生了什么?
from django import forms
from django.core.exceptions import ValidationError
from .models import Case, Person, Opp, Category
class MyFileField(forms.MultiValueField):
def compress(self, data_list):
# I'll get to this once the attr error goes away
pass
def __init__(self, *args, **kwargs):
fields = (
forms.URLField(), forms.FileField()
)
super(MyFileField, self).__init__(fields=fields, *args, **kwargs)
class CaseForm(forms.ModelForm):
class Meta:
model = Case
fields = ['title', 'file', 'categories']
widgets = {
'file': MyFileField
}
答案 0 :(得分:1)
问题是你在抽象类上调用 init 。
super(MyFileField, self).__init__(fields=fields, *args, **kwargs)
但基类是抽象的。
查看https://docs.djangoproject.com/en/1.8/ref/forms/fields/#multivaluefield
和
Python's super(), abstract base classes, and NotImplementedError