I'm using Django model inheritance to create two models - WorkAttachmentPicture
and WorkAttachmentAudio
class WorkAttachment(models.Model):
""" Abstract class that holds all fields that are required in each attachment """
work = models.ForeignKey(Work)
added = models.DateTimeField(default=datetime.datetime.now)
views = models.IntegerField(default=0)
class Meta:
abstract = True
class WorkAttachmentFileBased(WorkAttachment):
""" Another base class, but for file based attachments """
description = models.CharField(max_length=500, blank=True)
size = models.IntegerField(verbose_name=_('size in bytes'))
class Meta:
abstract = True
class WorkAttachmentPicture(WorkAttachmentFileBased):
""" Picture attached to work """
image = models.ImageField(upload_to='works/images', width_field='width', height_field='height')
width = models.IntegerField()
height = models.IntegerField()
class WorkAttachmentAudio(WorkAttachmentFileBased):
""" Audio file attached to work """
file = models.FileField(upload_to='works/audio')
One work can have a multiple audio and video attachments, so I'm using a modelformset_factory to create the forms:
class ImageAttachmentForm(forms.ModelForm):
""" Image attached to work """
image = forms.FileField(
label=_('File'),
help_text=_('JPEG, GIF or PNG image.')
)
description = forms.CharField(
widget=forms.Textarea(),
label=_('File description'),
help_text=_('Max. 500 symbols.'),
max_length=500
)
class Meta:
model = WorkAttachmentPicture
fields = ['image', 'description']
ImageAttachmentFormSet = modelformset_factory(WorkAttachmentPicture, form=ImageAttachmentForm)
class AudioAttachmentForm(forms.Form):
""" Audio file attached to work """
file = forms.FileField(
label=_('File'),
help_text=_('MP3 file.')
)
description = forms.CharField(
widget=forms.Textarea(),
label=_('File description'),
help_text=_('Max. 500 symbols.'),
max_length=500
)
class Meta:
model = WorkAttachmentAudio
fields = ['file', 'description']
AudioAttachmentFormSet = modelformset_factory(WorkAttachmentAudio, form=AudioAttachmentForm)
Everything seems correct to me, but at the project startup I get the error:
metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
If I create only one formset ( ImageAttachmentFormSet
, for example) everything is ok. But when I'm adding another one, error appears. How do I solve this, to use modelformsets with inherited models?
Solved it. If you look carefully
# this has forms.ModelForm
class ImageAttachmentForm(forms.ModelForm):
# this has forms.Form
class AudioAttachmentForm(forms.Form):
I've changed forms.Form
to forms.ModelForm
and everything works now - this was a simple copy/paste error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.