2π
β
By looking at Django docs what you get when you do img = request.FILES['avatar']
is a file descriptor that points to an open file with your image.
Then you should to dump the contents in your actual avatar
path, right?
#Here is where I create the name of the path to save as a VARCHAR field, THIS WORKS TOO
avatar = "../../static/profile/" + str(request.session['user_id']) + "/" + str(img)
# # # # #
with open(avatar, 'wb') as actual_file:
actual_file.write(img.read())
# # # # #
return redirect(request, 'myapp/upload.html')
Beware: the code is untested.
π€Savir
3π
You can pass a callable to upload_to
. Basically, what it means is whatever value that callable returns, the image will be uploaded in that path.
Example:
def get_upload_path(instance, filename):
return "%s/%s" % (instance.user.id, filename)
class MyModel:
user = ...
image = models.FileField(upload_to=get_upload_path)
Thereβs more information in the docs and an example too, though similar to what I posted above.
π€xyres
0π
from django.shortcuts import render
from django.conf import settings
from django.core.files.storage import FileSystemStorage
def uploadimage(request):
if request.method == 'POST' and request.FILES['avatar']:
img = request.FILES['avatar']
fs = FileSystemStorage()
#To copy image to the base folder
#filename = fs.save(img.name, img)
#To save in a specified folder
filename = fs.save('static/profile/'+img.name, img)
uploaded_file_url = fs.url(filename) #To get the file`s url
return render(request, 'myapp/upload.html', {
'uploaded_file_url': uploaded_file_url
})
return render(request, 'myapp/upload.html')
π€Merrin K
- [Django]-Localization with django and xgettext
- [Django]-Reverse for 'userlist' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
- [Django]-How to set Secure Cookie on WSGI applications in python
- [Django]-How to delete ONLY m2m relation?
Source:stackexchange.com