My App needs to upload different profile images in different folders inside the static folder. One more thing, I'm not using models, I just want to take the picture I choose in html input file and copy to the specific folder.
Here is my folder tree. Where I want to save the uploaded image is in MYPROJECTFOLDER/static/profile/<TheUserSpecificFolder>/
that's where I don't want to use MEDIA_ROOT
, becouse in media root I can't create a specific folder to each user. (I don't know if this is correct, if there is a way to create a specific folder to each user in the /media/ folder without using ImageField
or FileField
, please tell me).
Here is my folder tree:
MYPROJECTFOLDER
|
|------myproject/
|
|------myapp/
|
|------static
| |-------profile
| |------folder_user1
| |------ uploadedpicture.jpg #Here is where I want to upload
| |------folder_user2
Here is my uploadpic.html
<form action="{% url 'upload' %}" enctype="multipart/form-data" method="POST">
{% csrf_token %}
<input type="file" name="avatar" accept="image/gif, image/jpeg, image/png">
<button type="submit">Upload</button>
</form>
Here is my views.py
from django.shortcuts import render, HttpResponse, redirect
from . import forms
import os
def upload(request):
img = request.FILES['avatar']
#This just create the folder where I want to save the image.
if not os.path.exists('static/profile/' + str(request.session['user_id'])):
os.mkdir('static/profile/' + str(request.session['user_id']))
#NOW HERE IS WHERE I WANT TO WRITE THE CODE THAT SAVE THE IMAGE INTO THE FOLDER I JUST CREATED
return redirect('companyedit')