How to serve files for download in django? - python

I know that derivatives of this question have already been asked. But those questions are outdated and I would like to hear some new answers for new versions.
I have a model and it has a file field in it.
class MyModel(models.Model):
field = models.FileField()
I can upload files with this model by using the admin panel of django and I can set its location with the MEDIA_ROOT settings variable. But I can't download this file in the view. I have tried given its URL but I usually get the "404 not found" error.
def download(request):
file = # code to get the the model instance.
context = {'file': file}
return render(request, template, context)
Here is the code in template:
Download Link
This throws a 404 error. I know why it throw this error. Because no url deffinitions exist for that url.
So, how can I download this file?
Django 1.8.7, Python 3.4.3, ubuntu 14.04

In development, you can do this to get MEDIA_URL active
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)

Related

Django imagefield isn't showing any photo in the template

I'm working on a bookstore using Django. I'm trying to save each book's cover in each book created by the user using imagefield. I implemented every step in Django documentation about using imagefield but it doesn't work.
settings.py(in main project):
MEDIA_DIR = os.path.join(BASE_DIR,'media')
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
in urls.py (main project):
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("book.urls")),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in models.py(the book app):
class books(models.Model):
cover = models.ImageField(upload_to='cover/co', blank=True)
When I want go admin I find that the photo is submitted (when I click on the photo url in database nothing is shown to me) but I don't find any created media folders and when I try to request the image in any template It isn't showed to me.
when I try to click on the photo in the database in admin this is shown to me:
enter image description here
These are the paths of the app, project and static:
enter image description here
I don't know where is the problem and how to solve it as this is my first time to use imagefiled in django model,,, it might be from the paths, the model or the urls so if there is any help.
Remove / at the beginning of your MEDIA_URL.
Simply you can try this way:
settings.py file:
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media')
In models.py file:
class books(models.Model):
cover = models.ImageField(upload_to='cover/', blank=True) #I have removed co from here
After adding above code don't forget to migrate
Try this and see if this is solves your problem

Django display user uploaded content

I have yet to wrap my head around django and URLs, and my confusion is now preventing me from doing what I feel like should be a very simple task.
I have successfully implemented file upload.
In my settings.py file, I have added the specifications for where to store the uploaded files and the URL Django should use to serve them.
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL= '/media/'
I also added the necessary line to urls.py to allow Django to serve files from MEDIA_URL.
from django.conf.urls import url, include
from django.contrib import admin
from login_app import views as login_app_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', login_app_views.login_user),
# creating registered namespaces for each app
url(r'^login/', include('login_app.urls', namespace = "login_app")),
url(r'^CMIRS/', include('dashboard_app.urls', namespace = "dashboard_app")),
url(r'^CMIRS/', include('submit_app.urls', namespace = "submit_app")),
url(r'^CMIRS/', include('filter_app.urls', namespace = "filter_app")),
url(r'^CMIRS/case/',include('report_app.urls', namespace = "report_app")),
url(r'^CMIRS/', include('search_app.urls', namespace = "search_app")),
url(r'^search/', include('haystack.urls')), ##used in navbar-search
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In an app report_app, I want the webpage to display a hyperlink that can be used to view an uploaded file. When I click on the hyperlink, I want it to request the URL to the uploaded file.
The upload looks like such in my models:
upload1 = models.FileField(upload_to = 'documents/%Y/%m/%d/')
I am having trouble figuring out what to use in the render(request) in my view and how to correctly code this in HTML. When I attempt to use "media", I get an error saying it cannot be matched.
Here is a snippet of the HTML I am trying:
<dt>Upload</dt><dd><tr><td>{{ case.upload1 }}</td></tr></dd>
I am also confused as how to set up my render(request) so that it knows to access media/, and then go to the correct documents/Y/M/D depending on the primary key.
You don't want to use the url tag here at all. Your media's URL is stored in your model, and has nothing to do with Django's path resolution logic. Just reference the url method of the field:
<a href="{{ case.upload1.url }}">
See the docs.
(Note also that serving files via your urls.py like this works in dev only; for prod you'll need to configure your webserver to do it.)

Django Rest get file from FileField url

I have created a django rest model which includes a FileField.
media = models.FileField(upload_to='media/%Y/%m/%d/', null=True, blank=True)
I also implemented serializer and ListCreateApiView. There I can able to upload a file. On POST request rest server uploads the file in folder and returns me the url. However, on get request, server return json content with the url. If I use the url for get request, server respond Page Not Found. How to download the uploaded file using django rest? Do I have to create separate view for the same? If so, how to do that?
Edit:
The resulting url is
http://localhost:8000/message/media/2015/12/06/aa_35EXQ7H.svg
You have to define MEDIA_ROOT, MEDIA_URL and register MEDIA_URL in urlpatterns to allow Django server to serve these files.
Follow these steps:
settings.py file:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media_root")
Append this in your main urls.py file to serve media files :
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)
Also, you don't have to add media again in upload_to attribute because it's prepended by MEDIA_URL, then the url will be /media/media/.
Here is a correct example:
media = models.FileField(upload_to='message/%Y/%m/%d/', null=True, blank=True)
and the url of the media will be:
http://localhost:8000/media/message/2015/12/06/aa_35EXQ7H.svg

Viewing images uploaded to Django Admin

I have a simple Django admin page that uploads images to a product description. Everything works until I try to view the image by clicking on its path in the products information. I get this error:
Page not found (404)
Request URL: http://0.0.0.0:6666/the_image.jpg
I'm guessing I need to declare something in urls.py, but I have no idea where to start. I also tried changing my media paths in settings.py but I always get errors if I change to anything other than '/'
model.py
class Image(models.Model):
product_image = models.ForeignKey(Product)
image = models.ImageField(upload_to='/')
settings.py
MEDIA_ROOT = '/'
MEDIA_URL = '/'
admin.py
class InlineImage(admin.TabularInline):
model = Image
class ProductAdmin(admin.ModelAdmin):
inlines = [InlineImage]
Docs are here https://docs.djangoproject.com/en/dev/ref/settings/#media-root
You need to set MEDIA_ROOT and MEDIA_URL in your settings file like this
MEDIA_ROOT = /var/www/example.com/media/
MEDIA_URL = /media
and your upload_to should probably be the model name or something to identify it.
image = models.ImageField(upload_to='image')
Then the link should point the /media/image/NAME_OF_IMAGE.png
You will also need to have urls.py setup to server media files. For production you would want to do this in nginx with an alias. See https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user-during-development
Which says:
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)

Django Tinymce js not loading

hi all
Im tryng to integrate a tinymce in a django admin page.
I've installed the django-tinymce module (http://code.google.com/p/django-tinymce/)
I followed the instructions so these are my files:
settings.py
INSTALLED_APPS = (
...
'tinymce',
)
TINYMCE_DEFAULT_CONFIG = {
'plugins': "table,paste,searchreplace",
'theme': "advanced",
}
TINYMCE_SPELLCHECKER = False
TINYMCE_COMPRESSOR = False
url.py
urlpatterns = patterns('',
# Example:
# (r'^uboPy/', include('uboPy.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^tinymce/', include('tinymce.urls')),
)
i have the tinymce's js in a folder in the root called media/js
In the model i've this line: text = tinymce_models.HTMLField()
when i run the server i don't get error but when i go in the admin area of my model the tinymce is not loaded. With firebug i see that the tinymce library give a 404 error but the path is correct.. i have some problem in my url.py?
thanks for the help
Are you just putting a folder in your project root called media/js? It actually needs to be served somehow from a url somewhere.
The JavaScript file is loaded via your browser, so it needs to be accessible to the internet where all of your other media lives. This part has nothing to do with django, so you shouldn't expect errors or URL issues.
Once you've solved that part, specify the URL where the file can be accessed via the TINYMCE_JS_URL settings parameter.
For example, on my setup, the js is..
TINYMCE_JS_URL = '/media/js/tiny_mce/tiny_mce.js'
With firebug i see that the tinymce
library give a 404 error but the path
is correct..
Are you saying you can visit this URL path and the JS file loads? What I'm saying is: how is the path correct if it's a 404?
I found out the django-tinymce documentation is outdated, i.e. partially wrong.
What I discovered is that different versions of tinymce and django-tinymce packages are not compatible.
I solved it adding some variables to my project/settings.py and altering the tinymce directory and file names.
django-tinymce urls.py had some hardcoded paths in it which assumed the directories were named "tiny_mce" when in reality they were named "tinymce", hcen I had to rename them, or change the django-tinymce urls.py.
# project setting.py
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_JS_DIR = os.path.join(STATIC_DIR, "js")
TINYMCE_JS_ROOT = os.path.join(STATIC_JS_DIR, "tiny_mce")
TINYMCE_JS_URL = os.path.join(TINYMCE_JS_ROOT, "tiny_mce.js")
#TINYMCE_JS_ROOT = os.path.join(STATIC_JS_DIR, "tiny_mce")
#TINYMCE_JS_URL = os.path.join(TINYMCE_JS_ROOT, "tiny_mce.js")

Categories

Resources