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')]
Related
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)
Examined the documentation of django and this post Django MEDIA_URL and MEDIA_ROOT but, I'm still having issues, at first It was a SQlight issue so, I updated to latest Django from Django 2 now I'm getting:
AttributeError: 'Settings' object has no attribute 'MEDIA_Root'
Settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT),
Also tried this:
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT),
Removed the comma at the end:
Bad Code:
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT),
Good Code:
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I guess you actually imported wrong settings. Re-check your actually code. Instead of importing this (upper-case):
from django.conf import Settings
you should import this (lower-case)
from django.conf import settings
Also, as was pointed in comments, this is an error (or you incorrectly pasted the code here):
'MEDIA_Root'STATIC_URL = '/static/'
I have a Django server setup on development as well as the production server. The development server loads the static files but the production server gives 404 on loading (although it renders the URL).
I have already used the collectstatic method to accumulate my static files.
settings.py:
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
urls.py (main_project)
from django.contrib import admin
from django.urls import path, include
from django.conf import settings # new
from django.conf.urls.static import static # new
urlpatterns = [
path('', include('stock_management.urls', namespace='stock_management')),
path('auth/', include('django.contrib.auth.urls')),
path('admin/', admin.site.urls),
]
# if settings.DEBUG: # new
# urlpatterns += static(settings.STATIC_URL,
# document_root=settings.STATIC_ROOT)
# urlpatterns += static(settings.MEDIA_URL,
# document_root=settings.MEDIA_ROOT)
urls.py (App: stock_management) :
from django.urls import path, include
from .views import *
from django.conf import settings
app_name = 'stock_management'
urlpatterns = [
# Stock:
path('', stock_list, name='homepage'),
path('stock/', stock_list, name='stock_list'),
path('stock/add', stock_create_view, name='add_stock'),
path('stock/<pk>/edit', stock_edit, name='stock_edit'),
# Item:
path('items/', item_list, name='item_list'),
path('item/<pk>/edit', item_edit, name='item_edit'),
path('item/<pk>/delete', item_delete, name='item_delete'),
# API
path('api/items', item_list_API, name='item_list_API'),
# Gallery:
path('items/gallery', item_gallery, name='item_gallery'),
]
# if settings.DEBUG:
# # test mode
# from django.conf.urls.static import static
# urlpatterns += static(settings.STATIC_URL,
# document_root=settings.STATIC_ROOT)
# urlpatterns += static(settings.MEDIA_URL,
# document_root=settings.MEDIA_ROOT)
I want my static files to load in the server also.
When you set DEBUG=False in settings.py Django stops serving static files. You need to configure a web server like Nginx for static files.
Here a helpful tutorial: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-local-django-app-to-a-vps
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.
I am a newbie so I might have done something stupid. running python 3.3 and Django 1.6.2.
When I run the local server via command line, this is the error I receive "P/1.1 404 1712" and error on the browser is "module not found" and the exception location direct me urls.py line 22;
document_root=settings.STATIC_ROOT)
this is a part of urls.py:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'signups.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
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)
This is how my settings.py looks:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/whattheheck/static/'
# Template location
TEMPLATE_DIRS = {
os.path.join(os.path.dirname(BASE_DIR), "whattheheck", "static", "templates"),
}
if DEBUG:
MEDIA_URL = '/whattheheck/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "whattheheck", "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "whattheheck", "static", "media")
STATICFLIES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "whattheheck", "static", "static")
)
Can someone help please?
You forgot one static in the import statement, see the documentation:
from django.conf.urls.static import static
# ^^^^^^ this one
Right now, it tries to use the static module as a function but obviously, it does not work. The error 'module' object is not callable is raised when you are trying to use a module object (for example os, sys or any third-party) as a callable (with a __call__ method).