Django Framework got Server Error 500 when DEBUG to False - django

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.

Related

Django : Media Files not displayed in templates

I am trying to create a blog and to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for Post images with an ImageField), the image is stored in /media/images correctly. But I can't display the image on my webpage. However, when I inspect my template with GoogleChrome, the path of my files are ok but there is a 500 error (Failed to load resource: the server responded with a status of 500 (Internal Server Error).
Media Settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'core/static'),
)
Project urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin' , admin.site.urls),
path("", include("authentication.urls")),
path("", include("app.urls")),
]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
App urls.py:
from django.urls import path, re_path
from django.conf.urls import include, url
from app import views
from . import views
urlpatterns = [
path('', views.index, name='home'),
url(r'^blog$', views.blog_view, name ='blog'),
url(r'^blog/(?P<id>[0-9]+)$', views.post_view, name ='blog_post'),
re_path(r'^.*\.*', views.pages, name='pages'),
]
Views.py
def blog_view(request):
query = Post.objects.all().order_by('-date')
context = {'post_list' : query}
return render(request, 'blog/blog.html', context)
Template : Blog.html
{% for post in post_list %}
<img src="{{ post.image.url }}" class="card-img-top rounded-top">
{% endfor %}
models.py
class Post(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255, blank=True)
image = models.ImageField(blank=True, upload_to="images/")
When I check in the google chrome console, I notice that my development server tries to read my jpg file as a txt file, I think my problem is related to this anomaly. Anyone have an idea how to solve my problem ?
This is because of CORS error error, your browser URL must be the same as that of the image. For example, if your project URL is http://127.0.0.1:8000/, your images should be http://127.0.0.1:8000/media/images/about-us-2.jpg not http://localhost:8000/media/images/about-us-2.jpg
The CORS policy suggests the "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at $somesite"
you can read more about it at https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors
you can to this
STATIC_ROOT = (
os.path.join(BASE_DIR, 'staticfiles'),
)
STATIC_URL = '/static/'
MEDIA_ROOT = (
os.path.join(BASE_DIR, 'media'),
)
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'core/static'),
)

Django Static Image Showing then Not Showing, Views Share Base Html File Where Static Logo image is

My logo which is in my djangoprojectdir/static/media/ folder is showing on my homepage but in none of my other views. I dont know why it doesnt show up on other pages it shares the same base.html file for the navigation bar and header. Currently hosted website in production on digital ocean, nginx, gunicorn. I am just trying to serve static files in production debug off for small project with no database. I have already collected static. The image only works on my IndexView. My other static image files relating to my objects seem to be rendering fine. I have been exhaustively trying to figure this out.
The Image code out of the base.html that is problematic is:
<a class="navbar-brand" href="{% url 'maps:index' %}"><img src="static/media/Dirt logo3.png" hieght="5" class="img-fluid" alt="Responsive image"> </a>
I have tried mapping with {{ MEDIA_URL }}/Dirt logo3.png and {{ STATIC_URL }} to no avail, Hardcoded would be fine if it worked.
from base.html
#bootstrap stuff here#
{% load static from staticfiles %}
<a class="navbar-brand" href="{% url 'maps:index' %}"><img src="static/media/Dirt logo3.png" hieght="5" class="img-fluid" alt="Responsive image"> </a>
{% block body %}
{% endblock %}
from settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'mysite', 'maps', 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'mysite', 'maps', 'static', 'media')
MEDIA_URL = 'static/media/'
MEDIA_DIR = os.path.join(BASE_DIR, "")
Views.py
# works on IndexView but not any other view
class IndexView(generic.ListView):
template_name = 'maps/index.html'
paginate_by = 20
def get_queryset(self):
return Location.objects.all()
context_object_name = 'location'
class NeeddirtView(generic.ListView):
template_name = 'maps/needdirt.html'
paginate_by = 20
def get_queryset(self):
return Location.objects.all()
context_object_name = 'location'
from maps/urls.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'maps'
urlpatterns = [
# /maps/
path('', views.IndexView.as_view(), name='index'),
# /maps/71/
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('register/', views.UserFormView.as_view(), name='register'),
path('login/', views.LoginView.as_view(), name='login'),
path('logout/', views.LogoutView.as_view(), name='logout'),
# /maps/companies/
path('companies/', views.CompView.as_view(), name='comp'),
# /maps/equipment/
path('equipment/', views.EquipView.as_view(), name='equip'),
#maps/
path('equipment/<int:pk>/', views.EquipdetView.as_view(), name='equipdet'),
path('location/add/', views.LocationCreate.as_view(), name='location-add'),
path('location/<int:pk>/', views.LocationCreate.as_view(), name='location-update'),
path('location/<int:pk>/delete/', views.LocationDelete.as_view(), name='location-delete'),
path('equipment/add/', views.EquipCreate.as_view(), name='equipment-add'),
path('equipment/<int:pk>/', views.EquipCreate.as_view(), name='equipment-update'),
path('equipment/<int:pk>/delete/', views.EquipDelete.as_view(), name='equipment-delete'),
path('quarry/', views.QuarryView.as_view(), name='quarry'),
path('quarry/<int:pk>/', views.QuarrydetView.as_view(), name='quarrydet'),
path('quarry/add/', views.QuarryCreate.as_view(), name='quarry-add'),
path('quarry/<int:pk>/', views.QuarryCreate.as_view(), name='quarry-update'),
path('quarry/<int:pk>/delete/', views.QuarryDelete.as_view(), name='quarry-delete'),
path('search/', views.search, name='search'),
path('test/', views.TestView.as_view(), name='test'),
path('needdirt/', views.NeeddirtView.as_view(), name='needdirt'),
path('havedirt/', views.HavedirtView.as_view(), name='havedirt'),
path('about/', views.AboutView.as_view(), name='about'),
]
from 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('', include('maps.urls')),
path('admin/', admin.site.urls),
path('maps/', include('maps.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Any help is greatly appreciated.
The problem is most likely due to your relative path. Try:
<img src="/static/media/Dirt logo3.png"... />
Note leading slash which makes it relative to root.
I do not like spaces in filenames, so I would change that, too.

How to manage media files on Windows?

I want to get media files for Django when developing application. But they just don't set up. This is my settings:
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR
STATICFILES_DIRS = (
STATIC_ROOT + '\\projectpackage\\static\\',
)
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR + '\\projectpackage\\media\\'
Templatetag:
<img class="img-responsive" src="{{ project.image.url }}" alt="">
Urls:
urlpatterns = [
url(r'^profile/', include(profile.urls)),
url(r'', include(authentication.urls)),
url(r'^project/', include(project.urls)),
url(r'^admin/', include(admin.site.urls)),
url(r'^', 'views.index', name='index'),
url(r'^markdown/', include('django_bootstrap_markdown.urls')),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(STATIC_URL, document_root=STATIC_ROOT)
urlpatterns += static(MEDIA_URL, document_root=MEDIA_ROOT)
I can't see my mistake, because I've tried every other advices in other questions. And everything works bizzare. Static files are running good, media uploading to media/prj_img, but when I try to show image at template I've got such strange result:
<img class="img-responsive" src="/media/C%3A/Development/projectdirectory/projectpackage/media/prj_img/wallhaven-131_od9FWLX.jpg" alt="">
How could I fix this media error? This is strange, because everything looks right. Why there are full path in url?
Edit:
BASE_DIR
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
Also I've figured out that I've got wrong upload_to and changed it to prj_img. Now I've got following link:
<img class="img-responsive" src="/media/prj_img/wallhaven-24700.jpg" alt="">
But still it's not displating.
I have a lot of comments on your code.
STATIC_ROOT location is not appropriate. With your settings collectstatic command will put everything in your project's directory. Change it like so:
STATIC_ROOT = os.path.join(BASE_DIR, 'static_files')
But take care, that this folder is accessable (both permissions and django-settings) in production.
Use os.path.join to join folders:
STATICFILES_DIRS = (
os.path.join(STATIC_ROOT, 'projectpackage', 'static')
)
This url pattern must be the last one and contain $:
url(r'^$', views.index, name='index'), # do not pass strings
These two url patterns do the same (docs):
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(STATIC_URL, document_root=STATIC_ROOT)
Moreover, you do not need them. Just ensure, that INSTALLED_APPS setting contains 'django.contrib.staticfiles'.

static_url not resolving correctly, django 1.4

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).

How to show an image in template uploaded from admin panel Django 1.3

I'm a newbie to django. I'm developing a project in django 1.3. Problem is I'm uploading a image from the admin panel
class About(models.Model):
image = models.ImageField(upload_to='about')
files = models.FileField(upload_to='about')
Here is my template tag
<img class="profile_pic" src="{{ about.image }}" />
My setting file is as below
MEDIA_ROOT = path("media/")
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
STATICFILES_DIRS = (
path('static/'),
)
I checked that image is uploaded to /media/about/image_name. Problem is it rendered in the template as "/about/imagename" but not shoing. When I manually go to that image url it showing a 404 error.
<img class="profile_pic" src="{{ about.image.url }}" />
UPDATE
Also in your urls.py:
if settings.DEBUG:
urlpatterns += patterns('',
(r'^' + settings.MEDIA_URL.lstrip('/'), 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT})
It worked!... After importing setting.MEDIA_ROOT in the urls.py file then I added a media rule so ITs working now..
BTW It also need
{{ about.image.url }}
as #zsquare(thanks) said earlier Here is the media rule
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT}),