Django Загрузка файла на S3
Как связать форму с загрузкой в AWS S3 и отображением аватара? (Используя views.py)
Мне просто нужно использовать мое текущее ведро, которое работает для статических файлов, для медиа после того, как я сделаю медиафайл приватным и доступным только для аутентифицированных пользователей.
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class Profile(AbstractUser):
""" bio = models.TextField(max_length=500, blank=True)
phone_number = models.CharField(max_length=12, blank=True)
birth_date = models.DateField(null=True, blank=True) """
avatar = models.ImageField(default='default.png', upload_to='users/', null=True, blank=True)
pages/forms.py
from django import forms
from django.core.files.images import get_image_dimensions
from pages.models import Profile
class UserProfileForm(forms.ModelForm):
class Meta:
model = Profile
def clean_avatar(self):
avatar = self.cleaned_data['avatar']
try:
w, h = get_image_dimensions(avatar)
#validate dimensions
max_width = max_height = 100
if w > max_width or h > max_height:
raise forms.ValidationError(
u'Please use an image that is '
'%s x %s pixels or smaller.' % (max_width, max_height))
#validate content type
main, sub = avatar.content_type.split('/')
if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']):
raise forms.ValidationError(u'Please use a JPEG, '
'GIF or PNG image.')
#validate file size
if len(avatar) > (20 * 1024):
raise forms.ValidationError(
u'Avatar file size may not exceed 20k.')
except AttributeError:
"""
Handles case when we are updating the user profile
and do not supply a new avatar
"""
pass
return avatar
settings.py
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
# Amazon S3 Buckets
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_DEFAULT_ACL = None
AWS_S3_SIGNATURE_VERSION = 's3v4'
AWS_S3_REGION_NAME = 'us-east-2'
AWS_STATIC_LOCATION = 'static'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION)
STATICFILES_STORAGE = 'portfolio.storage_backends.StaticStorage'
MEDIAFILES_LOCATION = 'media'
DEFAULT_FILE_STORAGE = 'portfolio.storage_backends.MediaStorage'
storage_backends.py
from django.conf import settings
from storages.backends.s3boto3 import S3Boto3Storage
class StaticStorage(S3Boto3Storage):
location = settings.AWS_STATIC_LOCATION
class MediaStorage(S3Boto3Storage):
location = settings.MEDIAFILES_LOCATION
default_acl = 'private'
file_overwrite = False
custom_domain = False
sidebar.html
{% block content %}
{% load static %}
<nav id="sidebar">
Hi {{ user.username }}!
{{user.avatar}}
<img class="profile-pic" src="{% static 'img/profile1.png' %}" >
<form method = "post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
<ul class='no-bullets'>
<li><a href="/">Dashboard</a></li>
<li><a href="/">Messages</a></li>
<li><a href="/">Documents</a></li>
<li><a href="{% url 'logout' %}">Log Out</a></li>
</ul>
</nav>
{% endblock %}