Reputation: 58
I'm kinda new to python and I'm creating a website that users can buy Hi-Res images and now I'm looking for a way to let user to download the images that they've bought, from the Django model, Here is my pic model:
class Pic(models.Model):
name = models.CharField(max_length = 60, blank = False)
description_sizes = models.TextField(blank = False, name = 'des_sizes', max_length = 360)
captured_time = models.DateField(blank = False)
price = models.IntegerField(blank = False)
preview = models.ImageField(upload_to = f'static/post/preview/', null = False, blank = False)
tags = models.CharField(max_length = 1000, blank = False)
image_files = models.FileField(upload_to ='posts/ogFiles', null = True, blank = False)
My views.py :
def singlePostView(request, pic_id = None):
pic = Pic.objects.get(id = pic_id)
print(pic)
context = {
'pic':pic,
}
return render(request,"post/single_post_view.html", context)
I'm looking for way to make a button or link to download the image_file from pic model in the single view, and I've been searching for this for couple of days now and I've just came across these : xsendfile module
or using serve like this :
<a href="/project/download"> Download Document </a>
and in urls.py:
url(r'^download/(?P<path>.*)$', serve, {'document root': settings.MEDIA_ROOT}),
well for xsendfile module it's not really an efficient way bc
and for the serve because it's not a protected url user can download other files in other paths.
is there any alternative solution for downloading from Django model??
Upvotes: 1
Views: 3558
Reputation: 1267
You need to tell the browser to treat the response as a file attachment.
According to Django document link This is how you can do -
response = HttpResponse(my_data, headers={'Content-Type': 'image/jpeg','Content-
Disposition': 'attachment; filename="foo.jpeg"'}).
Read about the Content-Disposition header.
Upvotes: 1
Reputation: 588
You can add "download" attribute inside your tag to download files.
<a href="/project/download" download> Download Document </a>
https://www.w3schools.com/tags/att_a_download.asp
source: https://stackoverflow.com/a/57803641/10178508
Upvotes: 2