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)
Related
I have a django project.
In order to set up my media url, I followed the django doc Django doc - Managing static files:
For example, if your MEDIA_URL is defined as /media/, you can do this by adding the following snippet to your urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
my settings.py:
# ....
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_URL = 'http://127.0.0.1:8000'
# ...
MEDIA_URL_REL = '/media/'
MEDIA_URL = BASE_URL + MEDIA_URL_REL
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
my urls.py:
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
urlpatterns = [
# ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My uploaded files are found in media root, but when I access media url [ http://127.0.0.1:8000/media/proof/img.pdf]for it, it returns HTTP 404 NOT FOUND.
Please don't make any url with hard coded. This is more than bad practice.
BASE_URL = 'http://127.0.0.1:8000'
You can't write like that.
Your solution,
settings.py
MEDIA_URL = '/media/'
urls.py
urlpatterns = [
.......
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Hope this works.
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 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)
I am trying to create my own thumbnails within the Django admin and I believe they are being properly pointed to. However I cannot view the thumbnail. This is what I see:
When I click on the thumbnail, I get redirected to this URL and all I see is an empty white page.
http://localhost:8000/media/media/Screen_Shot_2016-04-08_at_12.55.25_PM.png
It is the correct URL but I do not see anything within the page.
Here is what code I have:
Within my settings.py
All files will go to cherngloong/uploads and /media/ will be the public front facing representation of the MEDIA_ROOT
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/media/'
Within cherngloong/cherngloong/urls.py I appended to the list to serve static files:
urlpatterns = [
url(r'^admin', include(admin.site.urls)),
url(r'', TemplateView.as_view(template_name="index.html"), name="index"),
url(r'^api/', include('api.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My cherngloong/api/urls.py:
urlpatterns = [
url(r'ig$', most_recent)
]
cherngloon/api/models.py:
class Media(models.Model):
...
...
file = models.FileField(upload_to="media/", default=None)
cherngloong/api/admin.py:
class MediaAdmin(admin.ModelAdmin):
search_fields = ["name", "file"]
list_display = ("name", "media_type", "url", "album", "display", "thumbnail")
def display(self, media_obj):
return '%s' % (media_obj.file.url, media_obj.file.name)
def thumbnail(self, media_obj):
location = media_obj.file.url
thumbnail_html = "<img border=\"0\" alt=\"\" src=\"{1}\" height=\"80\" />".format(location, location)
return thumbnail_html
thumbnail.allow_tags = True
display.allow_tags = True
Project structure:
I can't see any inconsistency on the code you have. I just created a project on GitHub with the same structure, and code you posted here, and everything worked like a charm, you can test it yourself, see the code here: https://github.com/vladir/cherngloong. I used the last version of Django, I know you are using a version below Django 1.9 because you are still using allow_tags, but even so your code seems good for me. Perhaps my code can help you to find what is happening.
I found why it is happening. Remove this line:
url(r'', TemplateView.as_view(template_name="index.html"), name="index"),
from your cherngloong/cherngloong/urls.py, and it will render ok.
It seems as this URL is too open, and it interferes with the thumbnails URL.
It could work for you instead:
url(r'^$', TemplateView.as_view(template_name="index.html"), name="index"),
I updated my code on the repo, so that you can test that it is working.
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".