How to download file from django admin - python

I created FileField in class Part in models.py. Also I get the link of this file by method file_link(self):
origin = models.FileField(upload_to='origin_files', null=True, blank=True)
def file_link(self):
try:
return "<a href='%s'>download</a>" % (self.origin.url,)
except PageNotAnInteger:
return "<a href=127.0.0.1:8000/main>download</a>"
file_link.allow_tags = True
In admin.py I added readonly_fields for file_link. Also I added in fieldsets file_link:
readonly_fields = ('file_link',)
fieldsets = (
('Характеристики плёнки', {
'fields': (....'data', 'origin', 'file_link')
}),
)
So, in my django admin I have FileField which allows to upload files to directory origin_files and link to this file. But when I click on this link I'm redirecting to home page of my site. For example, I downloaded file presentation.pptx. When I get url of this file I get
http://127.0.0.1:8000/admin/description/part/12/change/origin_files/Presentation.pptx
How I can download this file?

You have to configure MEDIA_URL in your django settings
https://docs.djangoproject.com/en/2.0/ref/settings/#media-url
Django builds your url the following way:
settings.MEDIA_URL + "origin_files/Presentation.pptx"
the MEDIA_URL default is an empty string, therefore you get the url "origin_files/Presentation.pptx" and your browser concatenates it to the current page, because the url doesn't start with a slash.
so you have to set the MEDIA_URL for example to '/media/'
then everything will work in your development environment.
On remote server this also requires configuring the web server appropriatelly for it to serve your MEDIA_ROOT to MEDIA_URL (out of the scope of this question obviously).

Related

I configured the media directory, but I can not access the image under the media directory [duplicate]

This question already has answers here:
How do I serve media files in a local Django environment?
(2 answers)
Closed 5 years ago.
I configured the media directory, but I can not access the image under the media directory:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/media/images/datadictionary/zfb.png
This is the setting in my settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
My directories in project, you see there is a zfb.png there:
My DataDictionary model is bellow:
class DataDictionary(models.Model):
appmodelfield = models.CharField(max_length=64, null=True) # app_model_field
name = models.CharField(max_length=16, help_text="总的名称")
content = models.CharField(max_length=32, help_text="内容")
image = models.ImageField(upload_to="images/datadictionary/", null=True, help_text="图标")
parentlevel = models.CharField(max_length=16, null=True, help_text="父级")
You can see my ImageField, and I also pip installed the pillow.
And the django rest framework web browser response data is:
[
{
"id": 5,
"appmodelfield": null,
"name": "支付类型",
"content": "支付宝",
"image": "http://127.0.0.1:8000/media/images/datadictionary/zfb.png",
"parentlevel": null
}
]
You see the image field, it is indeed the directory image you see upper.
But I can not get the image in my browser.
Add this to your Project url.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is for Development environment only,when the DEBUG=False in your settings.py(in production environment),Django no longer handle static file and media file anymore,static file and media file will be handle by web server like apache etc.

downloadable file link in django tables

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)

Django Rest app not using media root correctly to serve images

I have a project that has 3 apps, one named stores with store models, products with product models, and api which is the rest framework app that serves the Json results to clients. I set the media root in settings.py as MEDIA_ROOT = '/photos/' and the upload works for both product and store models. The main problem here is that for some reason the rest framework returns a url that references the api app instead of the products or stores apps for the media root url. here are my models
class Product(models.Model):
def get_image_path(instance, filename):
return '/Products/' + filename
picture = models.ImageField(width_field=None, max_length=100, blank =True, null =True)
store:
class Store(models.Model):
def __str__(self):
return self.name
def get_image_path(instance, filename):
return os.path.join('productphotos', 'stores', filename)
picture = models.ImageField(width_field=None, max_length=100, blank =True, null =True)
How do i set the mediaroot to the project directory instead so that all apps in the project reference it as mediaroot instead of themselves?
The upload works and upoads the pictures to the instructed directories in the root of the project (where manage.py is found), but the rest framework thinks it should get the media from the api app.. what's the proper way of doing this? here are screenshots:
the path uploaded to
the path returned in json
The MEDIA_URL setting is the URL path in the browser. The MEDIA_ROOT setting is the root directory on your server, and should be an absolute path.
MEDIA_URL = '/pictures/'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploaded_pictures')
Also, if you want Product and Store pictures to go into different sub directories, for example pictures/products/ and pictures/store/, you'd need to set the upload_to argument on the model field. For example
picture = models.ImageField(upload_to='products/', ... )
Edit: To serve static and media files during development, add this at the end of the urls.py
if settings.DEBUG:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(
settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

ImageField in Django 1.5.4 -- dealing with the images' paths

I am using Django 1.5.4 and I have a project with the following structure:
django_site
-django_site
-books # the app
-media
-images
-books
-authors
-static
-images
-templates
This is the necessary code:
# settings.py
MEDIA_ROOT = '/root/django_site/books/media/'
MEDIA_URL = '/media/'
# models.py
class Book(models.Model):
image = models.ImageField(upload_to="images/books/")
# urls.py
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^books/$', 'books.views.get_all_books'),
)
My problem is that, after adding the image via the admin site, if I click on the image link below the upload button a 404 page shows up, complaining the path does not exist.
The request URL is http://127.0.0.1:8000/media/books/media/images/book/out_of_control_1.JPG but in fact I want the result to be /root/django_site/books/media/images/out_of_control_1.JPG.
How do I fix that? Looking forward to your responses.
Since you seem to use the developpement server, I think your issue is related to this one : Django MEDIA_URL and MEDIA_ROOT
As explained in the answer, you have to set up a specific URL pattern for media handling when debug is set to True.
You can also have a look at the docs regarding this question.

Django - serving user uploaded images

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

Categories