static_url not resolving correctly, django 1.4 - django

I have an installed app (django_tables2) with its own static files folder but am having issues serving these using {{ STATIC_URL }}. After reading the django docs, if I run
>>> python manage.py findstatic django_tables2/themes/paleblue/css/screen.css
findstatic indeed correctly locates the one matching file within the apps directory of site-packages.
My template for the page in question contains:
{% block extrahead %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}django_tables2/themes/paleblue/css/screen.css" />
{% endblock %}
And related blocks exist in the parent template.
This page is served at http://127.0.0.1:8000/todo/product_groups/Analytical/. However, when running the development server I get a 404 for the css as its pointing to the wrong location:
GET /todo product_groups/Analytical/django_tables2/themes/paleblue/css/screen.css HTTP/1.1 404 2942
What's going on and why isn't the server following {{ STATIC_URL }} the same way as findstatic? I had this same static_url css working before doing some url redesigns, but can't seem to make it work in the new design. Any help or insight would be much appreciated.
Relevant snippets from settings.py:
MEDIA_URL = '/media/'
STATIC_ROOT = 'C:/Users/riedldar/Documents/Code/Arclin/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
"C:/users/riedldar/Documents/Code/Arclin/Arclin/static",
)
INSTALLED_APPS = (
....
'django.contrib.staticfiles',)
# Required for tables2
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request",
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
from urls.py:
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Arclin.views.home', name='home'),
# url(r'^Arclin/', include('Arclin.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
# Todo/Task manager
url(r'^todo/', include('todo.urls')),
# Login/out
url(r'^login/$', 'django.contrib.auth.views.login'),
url(r'^logout/$', 'Arclin.views.logout_page'),
# User Homepage
url(r'^$', 'todo.views.user_home'),
#
)
and todo\urls.py
from django.conf.urls.defaults import *
#from models import ProductGroup
urlpatterns = patterns('',
(r'^product_groups/([\w-]+)/$', 'todo.views.items_by_product_group'),
url(r'^task/(?P<task_id>\d{1,6})$', 'todo.views.view_task', name='todo_task_detail')
)

Is todo.views.items_by_product_group rendering your template with RequestContext, or one of the shortcuts or generic views that include it? If not, your template context processors won't be applied to add variables like STATIC_URL to your page context, resulting in the behavior you're describing.
As an aside, Django 1.4 introduces a new {% static '…' %} template tag, which lets you refer to static files without needing STATIC_URL from the context. Using that should also prevent this problem (but you'll probably still want to investigate if or why RequestContext is missing: that's usually a bug).

Related

Django deployment Failed to load resource: the server responded with a status of 404 (Not Found)

I have some product pictures uploaded in media folder that displays fine in development server, but after deployment I receive the 404 ressource not found error.
In settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),
os.path.join(BASE_DIR, 'node_modules')]
STATIC_ROOT = os.path.join(BASE_DIR, 'productionStatic')
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
In urls.py
from django.contrib import admin
from django.urls import path
from index import views
from index.views import indexPage, hdnytorv
from webshopRestaurant.views import hd2900_webshop_Main, AddressCheckForDeliverability, ChangeItemQuantity
from webshopCustomer.views import TakeawayCheckout, totalPriceDeliveryPossible, DeliveryForm, PickUpForm, localDeliveryCheckoutAddressCheck, Payment, PaymentComplete
from django.conf import settings
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = [
path('admin/', admin.site.urls),
path('', indexPage.as_view(), name = 'index'),
path('hdnytorv', hdnytorv.as_view(), name='hdnytorv'),
path('hd2900', views.hd2900.as_view(), name='hd2900'),
path('hd2900_takeaway_webshop', hd2900_webshop_Main.as_view(), name="hd2900_takeaway_webshop"),
path('check-address-for-deliverable', AddressCheckForDeliverability.as_view()),
path('changeItemQuantityInBasket', ChangeItemQuantity.as_view()),
path('isPriceAboveDeliveryLimit', totalPriceDeliveryPossible.as_view()),
path('hdbynight', views.hdbynight.as_view(), name='hdbynight'),
path('takeawayCheckout', TakeawayCheckout.as_view()),
path('deliveryFormCheckout', DeliveryForm.as_view()),
path('pickupFormCheckout', PickUpForm.as_view()),
path('local_delivery_checkout_is_address_deliverable', localDeliveryCheckoutAddressCheck.as_view()),
path('localDeliveryPayment', Payment.as_view()),
path('paymentComplete', PaymentComplete.as_view()),
]
#When in production medida url must always be added to urlpatterns
#if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
To display the product in view I have in my html template
<img class="card-img embed-responsive-item" src="{% get_media_prefix %}{{ item.product.image_path }}" alt="{{item.meta_description}}">
The pictures are uploaded to this location django_project_folder/media/productImages. I have assured that it is owned by www-data group and also media and all subfolders have 775 access rights. In development server the images shows up all right but in production I got 404 not found error.
This issue is a duplicate. See the answer here I fixed it by adding in urls.py
from django.urls.conf import re_path
from django.views.static import serve
re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),

Django Framework got Server Error 500 when DEBUG to False

I am using Django framework for project. I am rendering the HTML templet
def index(request):
print(" --- check fine?") # for print debug
trees = Tree.objects.all()
print(trees)
return render(request, "index.html", {'trees': trees})
--- check fine?
<QuerySet [<Tree: Tree object (8)>, <Tree: Tree object (10)>, <Tree: Tree object (11)>, <Tree: Tree object (12)>]>
[06/Feb/2021 17:28:44] "GET / HTTP/1.1" 500 145
these are my urls.
urlpatterns = [
path("", views.index, name="index"),
path('about/', views.about , name='about'),
path('contact/', views.contact , name='contact'),
path('upload/', views.upload_file , name='upload'),
]
DEBUG = False I am getting above error.
when I set my
DEBUG = True every thing works fine means show index.html and shows even data too.
setting DEBUG = False make difficult to find an error.
index.html contains below code which fetches data.
{% for tree in trees %}
<article class="col-lg-3 col-md-4 col-sm-6 col-12 tm-gallery-item">
<figure>
<img src="{{tree.image.url}}" alt="Image" class="img-fluid tm-gallery-img" />
<figcaption>
<h4 class="tm-gallery-title">{{tree.name}}</h4>
<p class="tm-gallery-description">{{tree.desc}}</p>
<!-- <p class="tm-gallery-price"></p> -->
</figcaption>
</figure>
</article>
{% endfor %}
and allowed hosts are.
ALLOWED_HOSTS = ['*','127.0.0.1','localhost']
Check this out:
Django returns an HTTP status code of 500, an Internal Server Error, when Django encounters runtime errors in a view, such as a syntax error or a view failing to return an object that Django expects. Closely related to errors in view logic is that Django itself will raise the TemplateDoesNotExist exception when an error is encountered in a view, the DEBUG setting is set to False, and a 500.html template is not found.
Beginning with Django 1.5 a new “allowed hosts” setting was introduced. When DEBUG is set to False, it is enforced. In your settings.py file, find the that looks like:
ALLOWED_HOSTS = []
and change it to include the Droplet’s IP address and/or the domain name pointing to your site. For example:
ALLOWED_HOSTS = ["example.com", "111.111.111.111"]
Source:
https://docs.webfaction.com/software/django/troubleshooting.html#:~:text=Django%20returns%20an%20HTTP%20status,an%20object%20that%20Django%20expects.
https://www.digitalocean.com/community/questions/server-error-500-django-digital-ocean
This are varible from settings.py
STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# STATICFILES_STORAGE = "whitenoise.storage.CompressedStaticFilesStorage"
due to STATICFILES_STORAGE collectstatic were using whitenoise engine. I comment STATICFILES_STORAGE .
I suggest to delete all STATIC_ROOT directry in above case /staticfiles folder.
and use
python manage.py collectstatic
to collect files.
and use this in url
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', include('ourhouse.urls')),
path('admin/', admin.site.urls),
# path('accounts/',include('accounts.urls'))
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
to use static and media files.

How to manage static files from Django 1.8 to Django 1.10

I have troubles with upgrading my project from Django 1.8 to Django 1.10: static files are not loaded anymore.
My template looks like this:
{% load staticfiles %}
<!DOCTYPE html>
...
<link href="{%static 'file.css' %}" rel="stylesheet">
...
Then in my file settings.py, I have 'django.contrib.staticfiles' as an installed app. DEBUG is set to True, and I have:
STATIC_URL = os.path.join(BASE_DIR, 'static/')
STATIC_ROOT= os.path.join(BASE_DIR,'static/')
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static/'), "./", ]
But when the html is produced, it is like the %static has no effect anymore. It is replaced by the empty string (the same works fine with Django 1.8, where the %static is replaced by the content of STATIC_URL). Does anyone know how to fix this ?
Can you added the Update the urls.py(mainproject/urls.py), once you made the chnages run the python manage.py collectstatic command.
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
===================
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
def root(folder):
return os.path.join(os.path.abspath(os.path.dirname(__file__)), '..',folder)
STATIC_ROOT = root('staticstorage')
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
root('static'),
)

serving static files django development

I know a million people have asked this, and I've read and read but still cannot get this to work (I think that says something about the documentation cough cough).
ONE. CSS:
Here are my settings:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'))
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static")
STATIC_ROOT = '/static/'
STATIC_URL = '/static/'
also relevant:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'blog',
)
My templates are serving up just fine, while my css is not. its located in static/originaltheme.css
I've tried both:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}originaltheme.css">
and
<link rel="stylesheet" type="text/css" href="/static/originaltheme.css">
TWO. Also, is there a way to get hardcoded urls to display? for example, lets say the content of a blog post has a hardcoded url to /static/img1.jpg, how can I do that? All of the documention points to {{ static_url }}, but im guessing that that wont get evaluated when returned from a text field of a database...
is there something to do with my urls?
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'nickswebsite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', 'blog.views.index'),
url(r'^blog/view/(?P<slug>[^\.]+)',
'blog.views.view_post',
name='view_blog_post'),
url(r'^blog/category/(?P<slug>[^\.]+)',
'blog.views.view_category',
name='view_blog_category'),
url(r'^admin/', include(admin.site.urls)),
)
EDIT:
I tried doing this is in the urls:
urlpatterns = patterns('',
url(r'^$', 'blog.views.index'),
url(r'^blog/view/(?P<slug>[^\.]+)',
'blog.views.view_post',
name='view_blog_post'),
url(r'^blog/category/(?P<slug>[^\.]+)',
'blog.views.view_category',
name='view_blog_category'),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=setting.STATIC_ROOT)
urlpatterns += staticfiles_urlpatterns()
but im getting a "settings" undefined error. I tried to import settings and im still getting an error.
Edit
Okay, the documentation for serving static off development server is HORRIBLE. Whoever wrote it should really rewrite it. This guy is the only person in the entire world who seems to explain this clearly: http://agiliq.com/blog/2013/03/serving-static-files-in-django/#servee
You DO need these in the settings.py (why arent they included in the initial installaion??? what genius...):
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
You do NOT need these:
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static")
STATIC_ROOT = '/static/'
You do NOT need:
manage.py collectstatic
http://agiliq.com/blog/2013/03/serving-static-files-in-django/#servee:
Points to be noted
We did not make any changes to any of the static settings provided by Django to us. We left the static settings as they were in default settings.py provided by Django.
You don't need any change in your urls.py for serving your static files in development. You don't need to add staticfiles_urlpatterns(). Many a times, I got confused with this.
You do not need python manage.py collectstatic for serving static files in development.
I also fought against this particular problem. And finally came up with this blog post
Actually you don't need collectstatic , STATICFILES_FINDER and django.contrib.staticfiles. They are all related. Read the blog post
I added these lines to the bottom of my url.py:
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
And this in my settings.py:
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Did you use:
./manage.py collectstatic
Also your STATIC_ROOT should be absolute path to the directory static files should be collected to:
STATIC_ROOT = os.path.normpath(os.path.join(BASE_DIR, "static"))
This is what I did for Django 2.0 using the above answers. So you'll want a system that makes deployment easy.
settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Serve Static in Development
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATICFILES_DIRS = [os.path.join(BASE_DIR, "appName/static/appName")]
# Serve static in production
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Then made a directory ~/documentRoot/appName/static/appName/ and copied my png into it. Then in my template:
<head>
<bootstrap,jquery,etc...>
{% load staticfiles %}
</head>
<body>
<img class="mb-4" src="{% static "myImage.png" %}" alt="" width="72" height="72">
</body>
Then when you want to deploy you just run collectstatic and they'll be served in one spot. Each time you add an app, add to that list of static dirs.

Django: Can't get homepage to display correctly TemplateDoesNotExist at /

well I'm working on a new Django project and am having a real hard time getting the index.html page to display correctly. Any advice on what to change to get it to display correctly?
I'm getting the error
TemplateDoesNotExist at /
index.html
my settings for each file are below.
myprojectname/myprojectname/settings.py
import os
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'templates/static')
TEMPLATE_DIRS = (
PROJECT_ROOT + '../templates'
)
myprojectname/myprojectname/urls.py
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', 'apps.views.index'),
url(r'^admin/', include(admin.site.urls)),
)
myprojectname/apps/views.py
from django.shortcuts import render_to_response
def index(request):
return render_to_response('index.html', locals())
I'm new to Django too so don't hate! :) I'll gladly admit I'm a noob...
Set up your template directories:
PROJECT_DIR = os.path.dirname(__file__)
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, 'templates'),
)
Your folder structure should be similar to:
project_name/
project_name/
settings.py
templates/
index.html
The folder structure is especially important!
And define your template loaders if you haven't already:
TEMPLATE_LOADERS = (
('django.template.loaders.cached.Loader', (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)),
)
I've wrapped the standard loaders with cached.Loader, which funnily enough just caches pre-compiled templates.
Also, while I'm here, fix your root URL:
urlpatterns = patterns('',
url(r'^$', 'apps.views.index'),
Note the extra $ terminating the end of the regex, otherwise this first URL will match every single URL, and none of the others will get a chance to match.
Try this..
TEMPLATE_DIRS = (
PROJECT_ROOT + '../templates/'/
)