django-将图像文件从表单保存到s3

时间:2018-07-09 20:13:03

标签: django python-3.x image amazon-s3

除图像外,表单中的所有内容都在保存。该图像也没有上传到我的s3存储桶。当我通过管理员保存表单时,图像确实会保存并上传。

models.py

class Profile(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, 
           on_delete=models.CASCADE, related_name='profile')
    slug = models.SlugField(blank=True,unique=True)
    location = models.ForeignKey(Location, on_delete=models.CASCADE, 
               null=True, blank=True, related_name='local')
    image = models.ImageField(upload_to=upload_image_path, null=True, 
            blank=True)
    bio = models.TextField(null=True, blank=True)
    active = models.BooleanField(default=True)

def __str__(self):
    return str(self.user.username)

forms.py

class ProfileEditForm(ModelForm):
    img = forms.ImageField(required=False)
    bio = forms.CharField(required=False)

    class Meta:
        model = Profile
        fields = ('img', 'bio')

views.py

@login_required
def profileEdit(request):
    title = "Update Profile"
    profile, created = Profile.objects.get_or_create(user=request.user)
    if request.method == 'POST':
        form = ProfileEditForm(request.POST, request.FILES or None, 
               instance=profile)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
            return redirect("profile")
    elif request.method == 'GET':
        form = ProfileEditForm()
        context = { "form": form, "title": title }
        return render(request, "account/profile_edit.html", context)

settings.py

AWS_ACCESS_KEY_ID = "***"
AWS_SECRET_ACCESS_KEY = "***"

AWS_FILE_EXPIRE = 200
AWS_PRELOAD_METADATA = True
AWS_QUERYSTRING_AUTH = True

DEFAULT_FILE_STORAGE = 'src.utils.MediaRootS3BotoStorage'
STATICFILES_STORAGE = 'src.utils.StaticRootS3BotoStorage'
AWS_STORAGE_BUCKET_NAME = 'mybucket'
S3DIRECT_REGION = 'us-east-1'
S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME
MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME
MEDIA_ROOT = MEDIA_URL
STATIC_URL = S3_URL + 'static/'
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'

import datetime

two_months = datetime.timedelta(days=61)
date_two_months_later = datetime.date.today() + two_months
expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT")

AWS_HEADERS = {
        'Expires': expires,
        'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), ),
}

utils.py

from storages.backends.s3boto import S3BotoStorage

StaticRootS3BotoStorage = lambda: S3BotoStorage(location='static')
MediaRootS3BotoStorage  = lambda: S3BotoStorage(location='media')

不确定要添加的更多信息,如果需要更多详细信息,请告诉我。谢谢!

0 个答案:

没有答案