Uploaded Image in django not working during production - python

During development my uploaded images are showing, but on production they are not.
Here are the codes:
#settings.py
STATIC_ROOT = '/home/eakdev/webapps/my_static'
MEDIA_ROOT = '/home/eakdev/webapps/my_static/media'
MEDIA_URL = '/media/'
#urls.py When I add this during development my images are showing correctly
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#base.html
<img class="img-responsive" src="{{ project.preview.url }}" alt="">
After reading some of the questions related to this, I think the reason why its not working is that my code is using dev server to serve the media files, which is only good for development. What do i change so that it would work in production?

The preferred way to serve media files in production is to set up your front-end webserver or CDN to serve them.
For example in nginx you'd include the following section in your server configuration:
location /media/ { # Should match MEDIA_URL
alias /path/to/mysite.com/media/; # Should match MEDIA_ROOT
}
And in Apache:
Alias /media/ /path/to/mysite.com/media/ # MEDIA_URL MEDIA_ROOT
<Directory /path/to/mysite.com/media> # MEDIA_ROOT
Require all granted
</Directory>
These would be the bare minimum directives and you can of course do a lot more with caching, access control, etc.

I had the same problem.
In settings.py i commented these lines:
#MEDIA_ROOT = '/home/prk/Documents/prakhar/mysite/media'
#MEDIA_URL = '/media/'
and added these lines:
MEDIA_ROOT = os.path.join(BASE_DIR, "..", "www", "media")
MEDIA_URL = '/media/'
When you will run server on localhost it will give error but in production it will work fine.
my project structure is:
/Wrapper/mysite/( ... and ... and manage.py and mysite and ...)
in wrapper directory i have a folder named www and inside it a folder named media.
Hope this helps.

Related

In django, what is correct setup for media deployment on python anywhere

I am trying to deploy my django app on python anywhere, but I believe media_urls or media_root may be set incorrectly. I also spent time trying to figure out how to print all valid urls on django, but nothing work for me on this link. Django : How can I see a list of urlpatterns?.
I received a "ModuleNotFoundError: No module named 'django.core.urlresolvers'"
from .base import *
DEBUG = False
ALLOWED_HOSTS = ["*"]
MEDIA_ROOT = os.path.join(BASE_DIR, "images")
MEDIA_URL = '/snapcapsule/'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
Answer
Your static file mapping for images is at at /images, but you're accessing the image from /snapcapsule/images. Either change your media_url or your static file mapping so that they match.
Most of the time, I server static and media with django at local and with nginx in server.
At local:
# at the end of urls.py
if settings.DEBUG:
# debug toolbar
import debug_toolbar
urlpatterns.insert(0, path("__debug__/", include(debug_toolbar.urls)))
# static and media
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns.extend(
staticfiles_urlpatterns()
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
)
In server:
# nginx.conf
server {
...
location /static/ {
alias /path/to/project/static_collection/;
}
location /media/ {
alias /path/to/project/media/;
}
}

Django media not loading, static files working

I'm trying to run a jango site, static files are working, media is not loaded from the media folder, if the picture in static files is visible. The folder is listed correctly, pycharm gives a fall in the folder
setings.py
STATIC_ROOT = '/home/static/'
STATIC_URL = '/static/'
# MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
MEDIA_ROOT = '/home/media/'
MEDIA_URL = '/media/'
urls.py
if settings.DEBUG:
import debug_toolbar
# Server statics and uploaded media
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
# Allow error pages to be tested
urlpatterns += [
url(r'^403$', handler403),
url(r'^404$', handler404),
url(r'^500$', handler500),
url(r'^__debug__/', include(debug_toolbar.urls)),
]
I use django oscar, this can be the cause of the problem?
To solve this problem, you should executed pycharm with run as administrator or apache service executed run as administartor ,or Enter the absolute path to the media file like:
"C:\Users\dr_r00t3r\DjangoProject\media"
Perhaps the access to the desired folder is not possible. To do this, you must run the following command:
chown -R $user:www-data /home/media/
or
chmod 755 -r /home/media
Yes, if I use full path to media, it's working.
like this:
MEDIA_ROOT = 'F:/Work/Mebli1/backup-7.30.2018_21-56-35_u6487/homedir/furniture/furniture/home/media'

Django: serving user uploaded files

I'm new to Django and Python.I want to display a link to my files stored in my static folder.Here is the required code from settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_URL = "/media/"
When I access these files through my admin I get the following url displayed in my browser:
http://127.0.0.1:8000/media/filename.pdf
Hence what I tried is to give a link to the file in my HTML code :
File
But instead of displaying http://127.0.0.1:8000/media/filename.pdf it just displays /media/filename.pdf which results in an error.
Adding localhost:8000/ before {{instance.docFile.url}} also didn't work.
Why isn't this working?What is the correct way to display link to my files?
Let me know if anything else is required.Thank you.
in 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)
in your settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/uploads/'
Then in your template
File
If you want know refer the docs Manage static files
The error is coming because your file is not stored in media.it is stored in static but your database store media URL. change your MEDIA_ROOT (given below) and try to upload one more time
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Don't put slash
:
File
Please see the Django setting MEDIA_ROOT documentation to better understand what your trying to do.
First MEDIA_ROOT and STATIC_ROOT must have different values.
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = '/media/'
See static files documentation for more details.
Second, You need to add these settings to your base 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)
If you want to use {{ MEDIA_URL }} in your templates, add 'django.template.context_processors.media' in the 'context_processors' option of TEMPLATES in settings.py.
At the top of your HTML page add {% load static %} then to display your media:
<img src="{{ MEDIA_URL }}{{ docFile }}" alt="test">
Please take your time with the Django Documentation, trust me it will help and also checkout the File upload settings

How to serve media files on Django production environment?

In me settings.py file :-
DEBUG = False
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_URL = '/static/'
LOGIN_URL = '/login/'
MEDIA_URL = '/media/'
In my urls.py file:-
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
When I am uploading the profile image then it is uploading to specified folder. but when i am visiting the user profile url then i am getting error like this in terminal
"GET /media/profile_images/a_34.jpg HTTP/1.1" 404 103
a_34.png is present in /media/profile_images/
then why it is not showing on browser and i am getting 404 error?
Django is not made to serve media file in production environment. You must configure the STATIC_ROOT settings and alias webserver to directly serve.
For example
If you are using apache web server in production, add the below to your virtualhost configuration
Alias /media/ /path/to/media_file/
<Directory /path/to/media_file/>
Order deny,allow
Allow from all
</Directory>
If you use Nginx you would have to use something like
location /media {
alias /path/to/media/file; # Change to your own media directory here.
access_log off;
}
Alternatively, you could also serve static files from AWS S3 or other cloud servers using django-storages
Django discourages to serve media files on production from the server. Use cloud services like amazon s3 to server your media files. See this Django doc serve media then give that path in MEDIA_URL.
You can use S3 Amazon for static and media files. It will be better.
Problem with S3 Amazon
Making the S3 bucket appear as part of the file system has terrible performance and fails randomly. When we are copying a lot of files it can take 10, 15, or 20 minutes for the copying to complete making deployments take a long time when they don’t need to. If we send these directly into S3 the same copy command takes about 1 minute to complete.
Solution
Subclass S3BotoStorage twice, one class for static files and the other for media files. This allows us to use different buckets and subdirectories for each type. (see: custom_storage.py)
Update settings
1. AWS_STORAGE_BUCKET_NAME needs to be bucket to hold static files and media files
2. MEDIAFILES_BUCKET
3. MEDIAFILES_LOCATION
4.DEFAULT_FILE_STORAGE
5.STATICFILES_BUCKET
6.STATICFILES_LOCATION
This is the subdirectory under the S3 bucket for the app
7.STATIC_URL
8.STATICFILES_STORAGE
Create custom_storage.py with the contents:
from django.utils.deconstruct import deconstructible
from storages.backends.s3boto import S3BotoStorage
from django.conf import settings
#deconstructible
class StaticS3Storage(S3BotoStorage):
bucket_name = settings.STATICFILES_BUCKET
location = settings.STATICFILES_LOCATION
#deconstructible
class MediaS3Storage(S3BotoStorage):
bucket_name = settings.MEDIAFILES_BUCKET
location = settings.MEDIAFILES_LOCATION
Sample settings.py.tmpl for updates settings (as mentioned above) based on my stack.json
MEDIAFILES_BUCKET = '<%= #node["apps_data"]["aws"]["buckets"]["bucket-name"] %>'
MEDIAFILES_LOCATION = 'folder_name_for_media_files_in_bucket'
DEFAULT_FILE_STORAGE = 'custom_storage.MediaS3Storage'
# If we're not using our S3 backend storage we need to serve the media files via path
if DEFAULT_FILE_STORAGE == "custom_storage.MediaS3Storage":
MEDIA_URL = 'https://%s.s3-website-us-east-1.amazonaws.com/%s/' % (MEDIAFILES_BUCKET, MEDIAFILES_LOCATION)
else:
MEDIA_URL = '/media/'
STATICFILES_BUCKET = '<%= #node["apps_data"]["aws"]["buckets"]["bucket-name"] %>'
STATICFILES_LOCATION = 'folder_name_for_static_files_in_bucket'
STATICFILES_STORAGE = '<%= #node["deploy_data"]["project_name"]["django_static_files_storage"] %>'
# If we're not using our S3 backend storage we need to serve the static files via path
if STATICFILES_STORAGE == "custom_storage.StaticS3Storage":
STATIC_URL = 'https://%s.s3-website-us-east-1.amazonaws.com/%s/' % (STATICFILES_BUCKET, STATICFILES_LOCATION)
else:
STATIC_URL = '/static/'
load static from staticfiles Django Template Tag
Change all uses of {% load static %} in templates to {% load static from staticfiles %}
The “static” from static files can make use of different back ends for files, including an S3 back end or local file back end. Using “load static” uses the Django template tags library which doesn’t handle different back ends.
Use this in the templates when including a static file and after including “static from staticfiles”:
{% static “path/to/the/file.ext” %}
This will figure out the full path to the file or if it’s in S3 it will insert a full URL to the file.
Example
<link rel="stylesheet" type="text/css" href="{% load static from staticfiles %}{% static "css/style.css" %}”>
Useful info
“django.contrib.staticfiles.storage.StaticFilesStorage” is the default Django static files backend
References
https://docs.djangoproject.com/en/1.9/howto/static-files/
https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/
For nginx it works for me with the following configuration lines:
location /media {
alias /home/ubuntu/speedy-net/media; # Change to your own media directory here.
access_log off;
}
Also see my related question on Code Review.
You need to setup a server to serve static content on production. When only Debug is True, static content is served by Django. So you need to
1) Setup a server
2) Point server media path to STATIC_ROOT directory
3) Run collectstatic command of django to collect all the static files to STATIC_ROOT.
Please refer
https://docs.djangoproject.com/en/1.10/howto/static-files/
The following method worked for me:
I added the following configuration in Apache config file:
alias /media/ /path/to/media/
<Directory /alchemus/django/WebForm/media>
Require all granted
</Directory>
settings.py file contained the following settings for MEDIA:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
Make sure you have the following settings in urls.py:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
The above setting is to make sure that django server only serves media files during development, serving media files in production should be handled by Apache server.
References: https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/modwsgi/#serving-files
Just add this code in urls.py
urlpatterns = [
.........
.........
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

Django 1.4 serving media files works, but not static

I am using Django 1.4 and for some reason i am able to serve media files, but not the static ones...
Here is my code:
settings:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
urls.py:
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_ROOT}),
base.html:
<link href="{{ STATIC_URL }}css/bootstrap.css" rel="stylesheet">
<link href="{{ MEDIA_URL }}css/bootstrap-colorpicker.css" rel="stylesheet">
i get a 404 http not found... what am i doing wrong? An i did create the static folder in my project right next to media
http://mysite.com:8000/static/css/bootstrap.css
Your static folder should be under one app that you use it for.
For example, I have a project named my_project and an application named my_app, I have some static files used in my_app so I put them under ~/project_path/my_project/my_app/static
NB: my_app must be in INSTALLED_APPS. See STATICFILES_FINDERS documentation.
Edit:
As a best practice, you should have a global static folder in one app (the main one), for example a static folder how contains your html template basic resources as jquery, bootstrap, your global style.
And for the static files how's required only for one app, for example app foo, these files should be under foo/static folder
I suggest removing the explicit media and static views and allowing the staticfiles app to create them (when DEBUG is True under development).
Check the default finders are present in your settings.py
https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/#std:setting-STATICFILES_FINDERS
Either add your project static directory to STATICFILES_DIRS (https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS) or place app specific static folders under each app. The app needs to be listed in the INSTALLED_APPS for the finders to locate the static content.
Do not place static files into STATIC_ROOT yourself. This directory is managed by the collectstatic command. See https://docs.djangoproject.com/en/dev/howto/static-files/#deployment
Here is how i define my media url in settings.py:
import os
ABSOLUTE_PATH = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(ABSOLUTE_PATH, '../media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(ABSOLUTE_PATH, '../static')
STATIC_URL = "/static/"
So like you see the difference is ../media and ../static
Is mysite in your installed apps ? Django look inside your installed apps and check if there's a static folder there.

Categories