BoJack Horseman
BoJack Horseman

Reputation: 4450

Getting the right url in a Django template

I wanted to make several files available to download for the users. I tried it like this but Django tries to open this url:

http://10.0.3.186:8000/var/www/openvpn/examples/easy-rsa/2.0/keys/first_key.key

I changed my template line like this:

<td width="100%" align = "right">
 <a href="http://10.0.3.186:8000/sslcert/{{ file }}/key_download">
  <font color = "white">&nbsp&nbspSSL-Key&nbsp&nbsp</font>
 </a>
</td>

I added following line to my urls

url(r'^(?P<username>\w+)/key_download$', views.key_download, name='key_download')

My views look like this

from django.utils.encoding import smart_str

def key_download(request, username):
    username_key = username + ".key"
    response = HttpResponse(mimetype='application/force-download')
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(username_key)
    response['X-Sendfile'] = smart_str("/var/www/openvpn/examples/easy-rsa/2.0/keys")
    return response

The file is getting downloaded and the filename is the right one, BUT it doesn't show any content at the moment.

Upvotes: 0

Views: 117

Answers (3)

BoJack Horseman
BoJack Horseman

Reputation: 4450

I solved the problem now.

def key_download(request, username):
    username_key = username +".key"
    fsock = open('/var/www/openvpn/examples/easy-rsa/2.0/keys/'+username_key, 'r')
    response = HttpResponse(fsock, mimetype='application/pgp-keys')
    response['Content-Disposition'] = "attachment; filename = %s " % (username_key)
    return response

A cool tip for the guys who might want to find out the mimetype

>>> import urllib, mimetypes
>>> url = urllib.pathname2url(filename)
>>> print mimetypes.guess_type(url)

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599956

/var/www is not a URL. It's a file path on your server. If you want users to access a file in that directory, you have to configure Apache (or whatever) to serve it at a particular address, and then use that URL in your template rather than the file path.

Upvotes: 0

0xc0de
0xc0de

Reputation: 8317

You also need to set the HTTP header of the response to something like application/force-download. Please see docs.

See also this question.

Upvotes: 1

Related Questions