Django Backend Image not displaying - python

I've tried many ways but nothing works.
I can't find a solution to this issue.
My frontend is React and My backend is Django.
On browser only show the URL path link of the image instead of an image.
I've tried to add this code to another template and It was working but this one does not work.
browser display
My settings.py file:
INSTALLED_APPS = ['django.contrib.staticfiles',]
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
My urls.py file:
from django.views.generic import TemplateView
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
if not settings.DEBUG:
urlpatterns += [re_path(r'^.*',
TemplateView.as_view(template_name='index.html'))]
My Model looks like this
class Product(models.Model):
name = models.CharField(max_length=200)
image = models.ImageField(blank=True)
description = models.TextField()
price = models.DecimalField(max_digits=9, decimal_places=2)
createdAt = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f" '{self.name}' "

this is my configuration, in my project React within Django, hope that could help
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
BASE_DIR / 'static',
BASE_DIR / 'frontend/build/static' //this is from react, frontend is the React project's name
]
MEDIA_ROOT = BASE_DIR / 'static/media'
STATIC_ROOT = BASE_DIR / 'staticfiles
dont forget to add/install corsheader(add it in INSTALLED_APPS also),and whitenoise
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
CORS_ALLOW_ALL_ORIGINS = True
urls.py
urlpatterns = [
path('', TemplateView.as_view(template_name='index.html')),
.....
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Related

Django Unable to load static files - internal-nginx-static comes in URL

Hope you are all having a very good Friday!
I am running a django project on nginx, and my project is each time going into this url - https://sitename.com/internal-nginx-static-location_uat/project_name/static/images/success.svg
I didn't configure this internal-nginx-static, and If I load the same project on another website, it works fine, is it something I can handle in code, or I have make changes in server conf.
Here is my URL.py Files
from django.conf import settings
from django.contrib import admin
from django.conf.urls.static import static
from django.urls import path, include
urlpatterns = [
path('', include('portal.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and settings file
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(DATA_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

React and Django routing problem in media file

When I am using re_path('.*',index,name='index') unable to route to my media locations and instead of re_path when i am using path('/',index,name='index') then my react app routing is not working.
so what should i do ?
from django.contrib import admin
from django.urls import path , include,re_path
from .views import index
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('api/bookdetails/', include('backend.api.urls', 'api')),
re_path('.*', index , name='index')
]
if settings.DEBUG:
urlpatterns+=static(settings.STATIC_URL , document_root=settings.STATIC_ROOT)
urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
setting.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "/static")
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "frontend/build/static")
]
MEDIA_URL = '/images/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'images')
The data form api is
{
"user": "exist",
"password": "valid",
"userdetails": {
"user_name": "laxman1006",
"full_name": "ajay nagpal",
"user_email": "Laxman#9451",
"college_name": "iitd",
"city": "luckonow",
"country": "india",
"profile_img": "/images/profile_image/laxman1006/laxman1006.jpg"
}
}
This is my serializer
class UserdetailsSerializer(serializers.ModelSerializer):
'''user details seriailizer '''
class Meta:
model = Userinfo
fields = ['user_name','full_name','user_email','college_name','city','country','profile_img']
Change it on your settings.py file and urls.py file as like below :
settings.py :
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static')
STATICFILES_DIR = os.path.join(BASE_DIR, '/static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py :
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('api/bookdetails/', include('backend.api.urls', 'api')),
]
if settings.DEBUG:
urlpatterns+=static(settings.STATIC_URL , document_root=settings.STATIC_ROOT)
urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Edited:
Add this inside your model UserInfo :
models.py :
def get_image_url(self):
img = self.profile_img
if img:
return img.image.url
else:
return None
serializers.py :
class UserdetailsSerializer(serializers.ModelSerializer):
'''user details seriailizer '''
profile_img = seriailizer.SerializerMethodField()
class Meta:
model = Userinfo
fields = ['user_name','full_name','user_email','college_name','city','country','profile_img']
def get_profile_img(self, obj):
request = self.context.get('request')
profile_img = obj.get_image_url()
return request.build_absolute_uri(profile_img)
I changed to this and now it is working
As that line was handling all of my url requests and my media files url was also handled by that so i just changed the sequence and now its working
from django.contrib import admin
from django.urls import path,include,re_path
from .views import index
from django.conf.urls.static import static
from django.conf.urls import url
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('api/bookdetails/', include('backend.api.urls', 'api')),
]
# urlpatterns += static(settings.MEDIA_URL,document_root= settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns+=static(settings.STATIC_URL , document_root=settings.STATIC_ROOT)
urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns+= [re_path('.*', index , name='index')]

Can not create media folder in Django Project

Media folder is not getting created when I run the server. I am working in localhost.
You can see the urls.py and settings.py code below.
I added 'django.template.context_processors.media' to the templates. My Django Version is 2.0.3 and I am using Python 3.6.8.
When I run the code, media folder should be created automatically. How can I fix that issue?
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #settings.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name = "index"),
path('about/', views.about, name = "about"),
path('articles/', include("article.urls")),
path('user/', include("user.urls")),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #urls.py
For a media file to be created,you need to add a slash after 'media' in the MEDIA_ROOT
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
instead of:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Django Media url returns 404 NOT FOUND

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.

Django static files not working on Heroku

My django application is working well on local server. But, when I deploy it on Heroku, the static files are not being served (getting a 404 error). Please help!
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('',
url(r'^$', 'product.views.home', name='home'),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
static files settings:
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "static", "media")
STATIC_ROOT = os.path.join(BASE_DIR, "static", "static_root")
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static", "static_dirs"),
)
WSGI file -
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "acton.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
try:
from dj_static import Cling
application = Cling(get_wsgi_application())
except:
pass
This is my setting for static files to deploy on Heroku.
Hope it will help :
import os
BASE_DIR = os.path.dirname(os.path.abspath(file))
STATIC_ROOT = 'staticfiles'
STATIC_URL ='/static/'
MEDIA_ROOT = os.path.join(PROJECT_PATH, "media")
MEDIA_URL = "/media/"
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Your setting.py file is incorrectly configured.Static and media files should be
STATICFILES_DIRS = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
For anyone else that comes across this problem, for me it was that I was missing the whitenoise configuration from my wsgi.py file.
Specifically the following was missing from my wsgi.py file:
from whitenoise.django import DjangoWhiteNoise
application = DjangoWhiteNoise(application)
Docs are here: http://whitenoise.evans.io/en/stable/

Categories