I want to download a file from the file field through Django views. I tried al lot but didn't get it. Now if I click on the media link it will show in the browser and I want to download it.
Thanks in advance.
models.py
class Question(models.Model):
title = models.CharField(max_length=254)
file = models.FileField(upload_to='exam/question')
def __str__(self):
return self.title
add your Folder path in setting.py file
Consider my folder name is media and that avaliable in where manage.py file is avaliable.
Add path in MEDIA_ROOT
settings.py
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
urls.py
add MEDIA_URL in appname>urls.py if you are access file from app.
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
#Add Your Path
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Download File
For localhost
http://localhost:8000/media/media/filename
Related
Today I tried to have images in my project and the idea is simple - create news with an image, title, and description.
I wonder why when I set up my media files
So I make my news in this view:
class NewsCreate(views.CreateView):
template_name = 'web/create_news.html'
model = News
fields = ('title', 'image', 'description')
success_url = reverse_lazy('home')
Here is the model:
class News(models.Model):
TITLE_MAX_LENGTH = 30
title = models.CharField(
max_length=TITLE_MAX_LENGTH
)
image = models.ImageField(
upload_to='news/',
blank=True
)
description = models.TextField()
Here is the set-up in settings.py:
MEDIA_ROOT = BASE_DIR / 'mediafiles'
MEDIA_URL = '/media/'
Here is the urls.py file:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('University_Faculty.web.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I've noticed that when I try to go to none existing URL this happens : wrong ulr page showing media as a correct one
This is the result in my media folder after 10+ POST requests it shows in the database that it is actually creating the news, but the images won't go anywhere: no files media folder
You need to correct
MEDIA_ROOT = BASE_DIR / 'media'
Hope this will work for you.
add this to settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
I am using django-tables2 and have a view which basically should allow user access to the data store. My table model has a link column is as follows:
class DummyTable(tables.Table):
download = tables.LinkColumn('dummy_download', args=[tables.A('pk')], orderable=False,
empty_values=(), verbose_name='')
The rendering of the link column is done as follows:
class Meta:
model = DummyModel
attrs = {'class': 'paleblue'}
def render_download(self):
url = static('cloud-download.png')
media_root = settings.MEDIA_ROOT
href = media_root + "/mask.nii.gz"
return mark_safe('<img src="' + url + '">')
So basically I have some data in my /media folder which I would like to allow the user to download when the link is clicked. However, I am unable to generate the correct link in the render_download method. Putting the link simply as I have it does not initiate any download even though it seems to point to the correct file location (locally). Also, I am not sure if this will work when someone connects remotely. I have a feeling it should call some reST API internally to initiate the download but I am not sure how to achieve this.
The settings.py file configures the media settings as follows:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I tried using the MEDIA_URL as the link but then it tries to match it with url configurations and returns with:
Using the URLconf defined in cloud.urls, Django tried these URL patterns, in this order:
^admin/
^$ [name='index']
^login/$ [name='login']
^logout/$ [name='logout']
^images/$ [name='images']
^static\/(?P<path>.*)$
The current URL, media/mask.nii.gz, didn't match any of these.
I think you should get the value of MEDIA_URL instead of MEDIA_ROOT:
def render_download(self):
url = static('cloud-download.png')
href = settings.MEDIA_URL + "/mask.nii.gz"
return mark_safe('<img src="' + url + '">')
You might need to add the following to your main urls.py so your media files can be served by the development web server.
# urls.py
...
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
# ...your routes...
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I am new to Django and I am currently having problems in showing uploaded images in Django Admin. I have followed many posted Q and A here in stackoverflow but of those worked in my problem. I hope any active of the coding ninja here could help me with this problem. Here is the detailed view of the problem:
I have defined the MEDIA_ROOT and MEDIA_URL in settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"
This is my upload model in models.py:
from django.utils.html import mark_safe
class ImageDetails(models.Model):
image = models.ImageField(null=True)
def image_img(self):
if self.image:
return mark_safe('<img src="%s" height="125px" width="125px"/>' % (self.image.url))
else:
return '(No image found)'
image_img.short_description = 'Thumbnail'
In my Application urls.py:
urlpatterns = [
url(r'^inputImage', views.inputImage, name='inputImage'),
url(r'', views.index),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In my admin.py:
class ImageDetailsAdmin(admin.ModelAdmin):
fields = ["image"] #for file upload
list_display = ("image_img",)
admin.site.register(ImageDetails, ImageDetailsAdmin)
The image was successfully stored at ProjectDIR/media. The HTML returns the url: http://127.0.0.1:8000/media/imagename.jpg at img tag. But the page fails to load the image (I will be redirected to index page whenever when using the url http://127.0.0.1:8000/media/imagename.jpg). I am using Django version 1.10
As suspected, this problem is about URLs in Django. The problem occurred because I declared the following urlpattern in an app urls.py:
url(r'', views.index, name='index'),
I solved the problem by changing the code to:
url(r'^$', views.index, name='index'),
And adding the following code at the project's main urls.py:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
first post so be gentle.
I am trying to display a static image in django. I can upload the image to my media directory but when I try to display it I get a nothing. If I copy the url to the browser I get ...
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/media/Will_and_Matt.jpg
Raised by: django.views.static.serve
detail.py
...
<img src="{{ student.photo.url }}" class="img-responsive">
...
model.py
class Student(models.Model):
photo = models.FileField( blank=True, null=True)
project urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^opencmis/', include('opencmis.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_URL)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_URL)
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
My update form works as it created the media folder and places images in it.
The URL pattern seems to match /media as it doesn't give an error there it just doesn't display the image.
Any ideas?
document_root=settings.STATIC_URL should be document_root=settings.STATIC_ROOT and similar for MEDIA_ROOT. You want the filesystem path in there, not the URL.
– dhke
I am having some problems with serving user uploaded files from my Django application:
from models.py:
class Picture (models.Model):
title = models.CharField(max_length=48)
date_added = models.DateTimeField(auto_now=True)
content = models.ImageField(upload_to='pictures')
From the Django admin the files get uploaded to the user_res/pictures/ folder.
from the project's settings.py:
MEDIA_ROOT = 'user_res'
MEDIA_URL = '/user_res/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
Every time I try to reference a static resource (namely css or js files), everything works fine using URLs such as
http://localhost:8000/static/<subfolder>/main.css.
However, I cannot access user uploaded files (which get created by the admin interface in the user_res/pictures folder with a relative URL such as
user_res/pictures/test.jpg
the URL is dynamically created with this line of code from a Django Picture model callable:
return '<img src="{}"/>'.format(self.content.url)
I have no dedicated url-s for either static or media files in the url.py file.
Does anybody have any idea as to how to make Django serve the media files? I understand that for live environments I will need to configure an http server to serve that particular directory, but for now I want to maintain a lightweight development suite.
Thank you.
Edit your urls.py file as shown below.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
edit your projects settings.py to look like:
#Rest of the settings
MEDIA_URL = '/media/'
MEDIA_ROOT = 'media'
STATIC_ROOT = ''
STATIC_URL = '/static/'
Please read the official Django documentation about serving files uploaded by a user carefully. Link to docs: https://docs.djangoproject.com/en/1.5/howto/static-files/#serving-files-uploaded-by-a-user
I think the url attribute returns a relative URL ( Django's FileField documentation ), so you should have:
return '<img src="{}"/>'.format(MEDIA_URL + self.content.url)
Relative URLs won't work, as a user visiting "http://localhost/books/" would be requesting "http://localhost/books/user_res/pictures/test.jpg".