How to serve files to download from HTML using django templating - django

I'm stuck in my project where i want to serve some files to download on clicking the download button on my webpage.
Can anyone kindly direct me how to serve downloadable files on the web pages using template in django.
in normal html, we can achieve as
<a href="<path_of_file>" download>
I am beginner in django. need some assistance with django templating
Generally, to render the dictionary text "{{ inser_me }}" in HTML and i created the entry in "views.py" as below.
def index(request):
my_dict = {'insert_me':"Now I am coming from first_app/index.html!"}
return render(request,'app/index.html',context=my_dict)
I saw about media file handling and added the below in "settings.py"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
and I put the contents under media directory. I can able to download the file if I use as "http://localhost/media/file_name"
can you please advise how i need to instruct in views.py to access this url.
<a href="{{ ?? }}" download>

Just replace with the file url in your template:
<a href="{{ my_file.url }}" download>

Related

Can't cope with images uploaded by a user during development

Django 1.9.7
Could you help me cope with user uploaded images. I have managed to save images.
But I can't show them. So far this is all about development stage (not production).
The bottommost code sample shows the html when I execute "View page source" in Chrome. This "src="/home/michael/workspace/..." is absolute path. It will work if I create such html and open it in the browser without a webserver.
But whey I run the Django dev server, the image doesn't show.
Could you give me a kick here.
/pharchive/pharchive/settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, '../media/')
MEDIA_URL = os.path.join(BASE_DIR, '../media/')
/pharchive/pharchive/urls.py
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
/pharchive/masterdocument/models.py
class Image(AbstractDocument):
image = models.ImageField(upload_to='images/%Y/%m/%d')
/pharchive/masterdocument/views.py
class ImageDetailView(DetailView):
model = Image
/pharchive/masterdocument/templates/masterdocument/image_detail.html
<html>
<img src="{{ object.image.url }}"/>
</html>
view-source:http://localhost:8000/images/6/
<html>
<img src="/home/michael/workspace/pharchive/media/images/2016/06/29/Screenshot_from_2016-02-23_205205.png"/>
</html>
MEDIA_URL should be the root URL for uploaded media, for example:
MEDIA_URL = '/media/'
You have set it to the path the the folder where uploaded media are copied.
Edit: as requested more information on how that works.
What you are trying to do is store an image file submitted by a user, and then serve it to other users. To store the file, you need to specify a location on the filesystem where to store it, in your case:
/home/michael/workspace/pharchive/media/images/2016/06/29/Screenshot_from_2016-02-23_205205.png
Django builds this path by concatenating these parts:
the MEDIA_ROOT
the ImageField's interpolated upload_to attribute, here 'images/%Y/%m/%d' interpolated to images/2016/06/29
the file name, here Screenshot_from_2016-02-23_205205.png.
Django also stores in the database the path to the file, relative to the MEDIA_ROOT, in your case images/2016/06/29/Screenshot_from_2016-02-23_205205.png
Now, to serve the stored file to your users, it first needs to be accessible through a URL, this URL is built by concatenating the MEDIA_URL setting to the path stored in the database (maybe modified to make it URL compatible), here it gives /media/images/2016/06/29/Screenshot_from_2016-02-23_205205.png.
The last step is to actually serve the file when the previously constructed URL is accessed, typically it will not be done the same way in development and in production.
In development, the Django devserver will be used to serve the file, which is why you add a url pattern when DEBUG is true. That url pattern will map any URL starting with the MEDIA_URL (/media/) to a view that will read the stored file and return its content.
In production you will use a dedicated web server to serve uploaded files, for performance reasons.

Live site not finding image file

I currently have the function of uploading images on my site. All the images are working uploading correctly, but when I try to display them using the image.url attribute in the view, it gives me a 404 not found error.
My believe it might be something with my Apache config or Django settings.py.
In my Apache config under I have:
Alias media/ /var/www/MySite/media/
<Directory /var/www/MySite/media>
Require all granted
</Directory>
In my settings.py:
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = 'media/'
In my view I am trying to display the image as follows:
{% for photo in photos %}
<div class="col-md-3 photo-wrapper">
<img src="{{ photo.image.url }}"/>
</div>
{% endfor %}
The image then looks for this url:
http://mysite.co.za/media/profile_photos/photo.png
But it doesn't find the image.
I did check that the image gets uploaded and it does to the correct location.
Also my model for clarification:
image = models.ImageField(upload_to='profile_photos')
Note: This is working fine when I work with the site on my localhost.
Edit:
So while I was trying different fixes I messed up some stuff that caused me to change the Debug in the settings.py to True, then I saw the image was actually being shown. I changed the debug to false again and the image was once again not showing. What would cause dubug to influence this?
The apache alias directive should start with a /
Alias /media/ /var/www/MySite/media/

django-ckeditor image upload giving wrong url of the image

When I try text editing and other text related stuffs and save it, the editor does its job nicely. But when I try to upload an image it just take a different url. I am on windows. Is it because of this, cause I saw a post on this post, but it didn't helped me either. It does get saved and they each have their own thumbnails too. But its just that the wrong urls.
I checked the src of the image, and it was like this,
<img alt="" src="/media/3/10/17Hydrangeas.jpg" />
But it should have been like this,
<img alt="" src="/media/2013/10/17/Hydrangeas.jpg" />
And sometimes the src of the image is just like this,
<img alt="" src="/media/3/10/17" />
This is the snippet of my settings.py:
CKEDITOR_UPLOAD_PATH = 'C:/Users/Nanyoo/web/demo/media'
MEDIA_ROOT = 'C:/Users/Nanyoo/web/demo/media'
I've included its url in my urls.py:
(r'^ckeditor/', include('ckeditor.urls')),
models.py:
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
from time import time
def get_upload_file_name(instance, filename):
return "uploaded_files/%s_%s" %(str(time()).replace('.','_'), filename)
class Blog(models.Model):
title = models.CharField(max_length=200)
image = models.ImageField(upload_to=get_upload_file_name, blank=True)
pub_date = models.DateTimeField(default=datetime.now)
creator = models.ForeignKey(User, related_name="creator_set")
body = models.TextField()
In the forms.py:
from django import forms
from django_summernote.widgets import SummernoteWidget
from ckeditor.widgets import CKEditorWidget
class BlogForm(forms.Form):
title = forms.CharField(max_length=200,widget=SummernoteWidget())
body = forms.CharField(widget=CKEditorWidget())
In the index.html:
{% for blog in blogs %}
<div id="page">
<h1>{{ blog.title | safe}}</h1>
<p>{{ blog.body | safe}}</p>
</div>
{% endfor %}
my form in the html:
{% block content %}
<form method="post" action=".">
{% csrf_token %}
<fieldset id="create_blog">
{{form.media}}
{{ form.as_p}}
<input type="submit" value="Post Blog" />
</fieldset>
</form>
{% endblock %}
I had a bit of a time getting django-ckeditor up and running with my Django app, but eventually hacked my way through to being able to serve uploaded files on the local machine (during development/testing).
First thing I suggest doing - if you haven't done so already - is read Django's documentation regarding static files. It may help in getting a better idea as to how things are configured and why.
From the django-ckeditor installation documentation, step 4 outlines the purpose of CKEDITOR_UPLOAD_PATH This works similarly to Django's built-in MEDIA_ROOT and STATIC_ROOT, where the path provided isn't necessarily the path in which the file is stored. You must specify a path to store the file upon upload. This may be done by making sure you have a MEDIA_URL global variable declared within your projects settings file.
Once you have the initial setup complete, the final step is to enable Django to serve the files you're working with locally. Please note: This method is to be used for development and debugging purposes only. Do not deploy your code with the following snippet included.
You may read more on this method via Django's static file how-to, within the "Serving static files during development" section.
In your project's urls.py file, add the following bit of code, enabling Django to serve your local data.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns(
'',
# existing url patterns,
# ...,
) + static(settings.MEDIA_URL, document_root=settings.STATIC_ROOT)
From there, you should be all set.
Just as a quick disclaimer: I am by far a seasoned professional. This method is what has worked for me, given my specific setup and environment. Results may vary.
Hope this helps to get you headed in the right direction. Best of luck!
CKEDITOR_UPLOAD_PATH is relative to MEDIA_ROOT.
https://github.com/django-ckeditor/django-ckeditor#id2
In your case it should be
CKEDITOR_UPLOAD_PATH = ''
This worked for me. To be honest, all these *_PATH issues were probably the hardest parts of Django for me.
UPD: I see that probably your issue was of some other sort. However I noticed the error in your configuration, that's why I wanted to fix that, since I had troubles with that and other people may find this issue and my answer too. Maybe your configuration was even right, if they've changed the defaults since the time of your post.
I made it !!!
Problem solved !!!!!!
I have the same problem just as you.
Did you solve that?
Did you change
CKEDITOR_UPLOAD_PATH = 'uploads/'
to something else?? Don't change if wrong.
Every time after I successfully upload the picture to the server using django-ckeditor, the django-ckeditor would request a URL which looks like this
uploads/2015/06/11/app_software_360.jpg
And that indicates the browser is requesting to
localhost:8000/somewhere/someplace/uploads/2015/06/11/app_software_360.jpg
but not localhost:8000/media/uploads/2015/06/11/app_software_360.jpg This is the actually right URL location, but django-ckeditor just can not find it out. I guess this has something to do with the settings.py
You can check out this page github issue
By adding these to settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = '/media/'
It works!
Thumb up if you think this is helpful. :)

Django - Displaying video with jwplayer

I am currently trying to display a video on a website using jwplayer. The view for the page is
def video(request):
return render_to_response('video_player/video.html', context_instance=RequestContext(request)
And the html template being used contains this in the head:
<script type="text/javascript" src="/jwplayer/jwplayer.js"></script>
And this in the body:
<div id="myElement">Loading the player...</div>
<script type="text/javascript">
jwplayer("myElement").setup({
file: "{{ MEDIA }}videos/test.mp4",
image: "{{ MEDIA }}videos/cute-bunny.jpg"
});
</script>
It doesn't display anything other than 'Loading the player', i think there may be something wrong with me calling the media_root. It is defined as:
MEDIA_ROOT = 'C:/Users/Timmy/Documents/GitHub/GroupProject/media'
You should be using the {{ MEDIA_URL }} tag in your templates, which you define in settings.py.
Example in settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT, like STATIC_ROOT, is the directory that Django uses to upload media files to and serve media files from, not the URL path.
See: https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user

Displaying image held in ImageField in a django template

I'm trying to display an ImageField image in my django template.
I'm doing it as such:
<img src="{{ pic.content.url }}" />
This, however, shows an image for mysite.com/appname/appname/picturename.ext. (which I'm like 90% sure is wrong; I don't know what's right, though. The images are kept in the larger django-site folder, and I don't know if apache can serve them directly by url)
My site settings.py file has the media directory correct (it uploads using the admin page and all that jazz), but this merely isn't working.
How do I show the image?
I am assuming you have done the required MEDIA settings. Make sure you are passing the RequestContext from your view and try changing your src to
<img src="{{MEDIA_URL}}{{pic.content.url}}" />
Update:
I think you need to change your media settings:
MEDIA_ROOT = '/var/www/mysite/media/' #This needs to point to the media folder
MEDIA_URL = '/media/'