1

I'm trying to make a custom form field in Django that allows a user to link a file or upload a file. To do this, I'm creating a subclass of the MultiValueField with the fields property set to (URLField(), FileField()). I'm not sure this is the right approach, but I keep getting an error I can't understand:

'MyFileField' object has no attribute 'attrs'

Here is my code. Can anyone explain what's going on?

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
        }
Ben Muschol
  • 608
  • 1
  • 5
  • 21

1 Answers1

2

The problem is that you are calling init on an abstract class.

 super(MyFileField, self).__init__(fields=fields, *args, **kwargs)

But the base class is abstract.

Look at https://docs.djangoproject.com/en/1.8/ref/forms/fields/#multivaluefield

and

Python's super(), abstract base classes, and NotImplementedError

Community
  • 1
  • 1
fiacre
  • 1,150
  • 2
  • 9
  • 26
  • After reading through the above references, I'm still confused. In the Django documentation link you provided, the code example makes a call to `super()` in the same way that you suggest is the problem: `super(PhoneField, self).__init__( error_messages=error_messages, fields=fields, require_all_fields=False, *args, **kwargs))` – mc_kaiser Dec 20 '17 at 21:24