I'm trying to make the local development work with everything under a /abc.
For example, instead of http://localhost:8080 I want everything to be at something like http://localhost:8080/abcd
I was able to achieve this by updating the url.py with the following:
urlpatterns = patterns('',
url(r'^abcd/admin/', include(admin.site.urls), name='admin'),
url(r'^abcd/search/?$', views.search, name='search'),
url(r'^abcd/$', views.index, name='root')
)
# Force Django to serve static assets, if this is not the production
if settings.PRODUCTION is False:
urlpatterns += patterns('', (
r'^abcd/static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT
}
))
Now I can view the pages with http://localhost:8080/abcd but the rendering does not show up correctly because of the static files. I need the static files to be served at http://localhost:8080/abcd/static/ and for it to work with all the pages.
Is there a simple way to make it work? I tried doing the above and it doesn't seem to work. I'm super new to django so I don't fully understand how I can achieve what I'm trying to do. Any help from experts would be much appreciated.
It should work.
urlpatterns = patterns('',
url(r'^abcd/', views.index, name='root')
url(r'^abcd/admin/', include(admin.site.urls), name='admin'),
url(r'^abcd/search/?$', views.search, name='search')
)
# Force Django to serve static assets, if this is not the production
if settings.PRODUCTION is False:
urlpatterns += patterns('', (
r'^abcd/static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT
}
))
change settings.py
STATIC_URL = '/abcd/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
Related
My static files only load on index page, but when navigating to another page like: examle_url/page, it returns a 404 error since it loads it like that: http://127.0.0.1:8000/categories/default/static/js/main.js, see the static loads after page
settings.py
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root/')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, '/static/base'),
)
urls.py "all my urls are in main directory and then i import views from apps"
urlpatterns = [
path('admin/', admin.site.urls),
path('profile/', profile, name="profile"),
path('', index, name="index"),
path('category/', category, name="category"),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
If it matters my load static files are all in theme.html file and is then extended in all other html files.
Any help will be greatly appreciated, thanks in advance!
You should prepend the STATIC_URL setting [Django-doc] with a slash:
# settings.py
# …
# with a leading slash
STATIC_URL = '/static/'
# …
If you do not do that, then the url will look like static/js/main.js. If the path does not start with a slash, then that is relative to path the current URL, and thus if the page is /categories/default, it will look at /categories/default/static/js/main.js.
I'm having a problem with django's URL system. I'm using Django 3. I have the following in my project's 'urls.py'
urlpatterns = patterns('',
url(r'^$', include('siteadmin.urls')),
)
and this in the 'urls.py' of a django app in the project, called 'siteadmin':
urlpatterns = patterns('',
url(r'^$', views.home, name='home'),
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.user_login, name='login'),
#...trimmed
)
With this setup, the following happens:
http://localhost/ => works perfectly, renders the 'home' view
http://localhost/register/ => breaks. (gives 404 and django's standard "The current URL, register, didn't match any of these.")
However, when I change the project's 'urls.py' to include the following:
urlpatterns = patterns('',
url(r'^app/', include('siteadmin.urls')),
)
And include /app/ in 1. and 2., both urls work perfectly. That is to say:
localhost/app/ => works perfectly
localhost/app/register => works perfectly.
What am I missing? Why does #2 break in the first case, but not the second?
Remove the dollar sign from the regex in the project urls.py:
urlpatterns = patterns('',
url(r'^', include('siteadmin.urls')),
)
I'm developing an Ajax site where routing is controlled with JavaScript.
I want every request to be sent to the IndexView except those declared in the urls.py file.
Here is my urls.py configuration:
urlpatterns = patterns('',
url(r'^api/', include('api.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', IndexView.as_view()),
)
If I change the regex to url(r'^', IndexView.as_view()) it works but files in MEDIA_ROOT won't be displayed.
I know in production I can config the server to serve the static files the way I want but I want it to work with the dev server.
Silly solution. Adding url(r'^', IndexView.as_view()) after,
if settings.DEBUG:
urlpatterns += patterns('',
(r'%s(?P<path>.*)' % settings.MEDIA_URL[1:], 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
did the job.
But I'm open to better ways for managing routing with this kind of ajax applications.
I know this question was asked many times, but none of the answers i found and tried helped me.
Those are my static files settings:
STATIC_ROOT = os.path.abspath(SETTINGS_PATH+'/staticfiles/')
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/staticfiles/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(os.path.dirname(__file__), 'static'),
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
And in myapp/urls.py:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
admin.autodiscover()
urlpatterns = patterns('',
# urls
)
urlpatterns += staticfiles_urlpatterns()
Collectstatic copies all files to staticfiles/ as it should and i get 404 on all static files.
I also tried this in urls.py:
if not settings.DEBUG:
urlpatterns += patterns('',
url(r'^staticfiles/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
)
This gives me following kind of errors:
Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:8000/?next=/staticfiles/css/bootstrap.css". localhost:11
Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:8000/?next=/staticfiles/css/style.css". localhost:12
Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:8000/?next=/staticfiles/js/bootstrap.js". localhost:79
Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:8000/?next=/staticfiles/js/login.js".
I can't see what's wrong with my settings. Any ideas are most welcome.
as you can see in the warning box in the docs, in production (i.e. with debug=False) you should be using your web server to serve static files, not django. For that reason, staticfiles will refuse to serve your assets if debug=False.
in settings.py::
if DEBUG:
STATIC_ROOT = os.path.join(BASE_DIR, '/static')
else:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
and in urls.py add
import django.views.static
urlpatterns += [
url(r'^static/(?P<path>.*)$', django.views.static.serve, {'document_root': settings.STATIC_ROOT, 'show_indexes': settings.DEBUG})
]
I'm using the code below in my root urls.py. You need to set FORCE_SERVE_STATIC to True in settings file if you want static and media to be served by django development server. And don't forget to run collectstatic command to update your static files.
from django.conf.urls.static import static
from django.conf import settings
<...>
if settings.DEBUG:
urlpatterns += static(
settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
elif getattr(settings, 'FORCE_SERVE_STATIC', False):
settings.DEBUG = True
urlpatterns += static(
settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(
settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.DEBUG = False
This is a late answer but may be this will help someone. There is an extra option to be used with runserver command which force Django to serve static files even when DEBUG=False
python manage.py runserver --insecure
Django docs ref: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#cmdoption-runserver-insecure
In your urls.py file:
add this line
from django.views.static import serve
add those two urls in urlpatterns:
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
With debug turned off Django won't serve static files for you any more .
Your production web server (Apache or Heroku or Pythonanywhere or something like this) should take care of that.
from django.views.static import serve
from django.conf import settings
if not settings.DEBUG:
urlpatterns += re_path(
r'^static/(?P<path>.*)$', serve, dict(document_root=settings.STATIC_ROOT)),
Note:
django.conf.urls.url() is deprecated in favor of django.urls.re_path().
def url(regex, view, kwargs=None, name=None):
warnings.warn(
'django.conf.urls.url() is deprecated in favor of '
'django.urls.re_path().',
RemovedInDjango40Warning,
stacklevel=2,
)
return re_path(regex, view, kwargs, name)
in my settings.py I have:
import os
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
# ... #
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
# ... #
STATIC_URL = '/static/'
in my urls.py I have:
urlpatterns = patterns('',
url(r'^', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
)
and in my template:
<img src="{{ STATIC_URL }}images/myimage.png">
Which doesn't work. The weird thing is that if I change my settings.py:
STATIC_URL = 'static/'
and my template to:
<img src="/{{ STATIC_URL }}images/myimage.png">
does work!! I have been chasing round in circle to fix this, and I have looked at lots of forum posts, but I can't seem to figure out what I'm doing wrong.
if you use staticfiles app you don't need this (assuming you are using Django 1.3):
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
})
Its handled by the app automatically. Try to remove and see what happens.