I have figured out a way to upload an image/file to s3 to a directory using the session key. It also works for uploading a file in general, not just s3.
First I added an attribute to the model to store the session key.
class TestS3Upload(models.Model):
session_key = models.CharField(max_length=50, null=False, blank=False)
...
Then I included a hidden field on the modelform that I pre-populated with the session_key
value in the view.
forms.py
class TestS3UploadForm(forms.ModelForm):
class Meta:
model = TestS3Upload
fields = ['file', 'session_key']
widgets = {'session_key': forms.HiddenInput()}
views.py
def test_s3_upload(request):
# create session if it doesn't already exist
if not request.session.session_key:
request.session.create()
session_key = request.session.session_key
...
form = TestS3UploadForm(initial={'session_key': session_key})
Then I created a function in my models.py
that returns a path using the session_key from the model and set the model's file field upload_to
attribute to this function
...
import os
def upload_to_session_key_dir(instance, filename):
return os.path.join(instance.session_key, filename)
class TestS3Upload(models.Model):
session_key = models.CharField(max_length=50, null=False, blank=False)
uploaded_at = models.DateTimeField(auto_now_add=True)
file = models.FileField(upload_to=upload_to_session_key_dir)
When saving the form now it uploads the file inside a directory with the session_key.
final views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import TestS3UploadForm
from .models import TestS3Upload
def test_s3_upload(request):
# create session if it doesn't already exist
if not request.session.session_key:
request.session.create()
session_key = request.session.session_key
if request.method == 'POST':
form = TestS3UploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
filename = "{}/{}".format(session_key, form.cleaned_data['file'].name)
s3_upload_path = TestS3Upload.objects.get(file=filename).file.url
return HttpResponse("Image successfully uploaded to bucket at location: {}".format(s3_upload_path))
else:
form = TestS3UploadForm(initial={'session_key': session_key})
return render(
request,
'upload/test_s3_upload.html',
{
'form': form
}
)
The template for the view test_s3_upload.html remained the same.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…