[Python] How to upload files into BinaryField using FileField widget in Django Admin?

Discussão em 'Python' iniciado por Stack, Setembro 24, 2024.

  1. Stack

    Stack Membro Participativo

    I want to create a model Changelog and make it editable from Admin page. Here is how it is defined in models.py:

    class Changelog(models.Model):
    id = models.AutoField(primary_key=True, auto_created=True)
    title = models.TextField()
    description = models.TextField()
    link = models.TextField(null=True, blank=True)
    picture = models.BinaryField(null=True, blank=True)


    title and description are required, link and picture are optional. I wanted to keep this model as simple as possible, so I chose BinaryField over FileField. In this case I wouldn't need to worry about separate folder I need to backup, because DB will be self-contained (I don't need to store filename or any other attributes, just image content).

    I quickly realized, that Django Admin doesn't have a widget for BinaryField, so I tried to use widget for FileField. Here is what I did to accomplish that (admin.py):

    class ChangelogForm(forms.ModelForm):

    picture = forms.FileField(required=False)

    def save(self, commit=True):
    if self.cleaned_data.get('picture') is not None:
    data = self.cleaned_data['picture'].file.read()
    self.instance.picture = data
    return self.instance

    def save_m2m(self):
    # FIXME: this function is required by ModelAdmin, otherwise save process will fail
    pass

    class Meta:
    model = Changelog
    fields = ['title', 'description', 'link', 'picture']


    class ChangelogAdmin(admin.ModelAdmin):
    form = ChangelogForm

    admin.site.register(Changelog, ChangelogAdmin)


    As you can see it is a bit hacky. You also can create you own form field be subclassing forms.FileField, but code would be pretty much the same. It is working fine for me, but now I'm thinking is there are better/standard way to accomplish the same task?

    Continue reading...

Compartilhe esta Página