[Answer]-Getting the right url in a Django template

0πŸ‘

βœ…

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)

1πŸ‘

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

See also this question.

πŸ‘€0xc0de

0πŸ‘

/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.

Leave a comment