简体   繁体   中英

How i can register on Django admin a field for upload of files

I'm trying use a lib boto3 for upload files in django admin, but i dont think i doing this correctly.

I'm trying to create a form class, and use it inside admin to upload

This my forms.py

from django import forms
from django.conf import settings
from .models import Invoice
import boto3
from botocore.exceptions import ClientError

class InvoiceForm(forms.ModelForm):
    file = forms.FileField(label='Arquivo', required=False)

    class Meta:
        fields = '__all__'
        model = Invoice

    def upload():
        s3 = boto3.client('s3')
        try:
            s3.upload_fileobj(file, settings.UPLOAD_BUCKET)
        except ClientError as e:
            logging.error(e)
            return False
        return True

And this my admin

from .forms import InvoiceForm

class InvoicesAdmin(admin.ModelAdmin):
    search_fields = ['name', 'user']
    list_display = ['name', 'user','value', 'installment', 'due_date', 'status', 'file']
    exclude = ['updated_by', 'created_by', 'attributes']
    autocomplete_fields = ['user']
    form = InvoiceForm

admin.site.register(models.Invoice, InvoicesAdmin)

I don't get an error, but the file is not saved to aws-s3

The upload method on InvoiceForm isn't being called. You'll need to call it from a method on the form which gets called by Django admin, for example when the form is saved.

Have a look here for how forms work in Django. https://docs.djangoproject.com/en/2.2/topics/forms/

Remember if you are overriding methods to call super.

The upload method as it stands will throw an error when it is called. Once the upload method is being called you can debug it from there.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM