django templateDoesNotExist at - python

Im getting a
templatedoesnotexistat / login.html
I copied and paste the settings from another project that worked and can not figure out why it can not find the template files. I have gone over it many times and copied the paths so they should defiantly be right. Its driving me mad
My file structure is
-virtual
-src
-logins
-dashboards
-static
-templates
-login.html
-static
-static-only
-media
settings.py
import os
BASE_DIR = '/Users/user/Documents/Python/virtual/'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'logins',
'dashboards',
)
ROOT_URLCONF = 'src.urls'
STATIC_URL = '/static/'
TEMPLATE_DIR = (
'/Users/user/Documents/Python/virtual/src/static/templates',
)
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = '/Users/user/Documents/Python/virtual/src/static/static-only/'
MEDIA_ROOT = '/Users/user/Documents/Python/virtual/src/static/media/'
STATICFILES_DIRS = (
'/Users/user/Documents/Python/virtual/src/static/static/',
)
urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'logins.views.login', name='login'),
url(r'^/accounts/auth/$', 'logins.views.auth_view', name='auth_view'),
url(r'^/accounts/dashboard/$', 'dashboards.views.dashboard', name='dashboard'),
url(r'^/accounts/logout/$', 'logins.views.logout', name='logout'),
url(r'^/accounts/invalid/$', 'logins.views.invalid', name='invalid'),
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)
views.py
from django.shortcuts import render, render_to_response, RequestContext
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/accounts/dashboard')
else:
return HttpResponseRedirect('/accounts/invalid')
def logout(request):
return render_to_response('logout.html')
def invalid(request):
return render_to_response('invalid.html')

You have TEMPLATE_DIR in your settings. It should be TEMPLATE_DIRS.

I doubt your template directory is inside the static directory: remove that part of TEMPLATE_DIRS.

In Django 1.8 template_dirs has been deprecated and is now expected to be defined using TEMPLATES["DIRS"]
The DIRS option
Changed in Django 1.8:
This value used to be defined by the TEMPLATE_DIRS setting.
Reference https://docs.djangoproject.com/en/1.8/ref/templates/api/#loader-types
Posting this as answer, since I wasted few hours on identifying the solution.

Related

Django Media Files Not Showing

My Django files are loading after upload and are shown in the media folder, however I cannot access them at localhost:<PORT>/media/<FILENAME._EXT>. I've looked at several other answers on stackoverflow and they haven't worked. For example adding the urlpatterns += static(...), having DEBUG=True in settings.py.
When accessing: http://localhost:8000/media/controller.gif:
Error:
lightchan-backend-1 | Not Found: /media/controller.gif
lightchan-backend-1 | 2022-03-06 16:37:34,875 WARNING Not Found: /media/controller.gif
In settings.py:
DEBUG = True
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
In my urls.py:
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('comment/<int:comment_id>/', views.comment, name='comment'),
path('comments/', views.comments, name='comments'),
path('reply/<int:incoming_id>/', views.reply, name='reply')
]
# if settings.DEBUG is True:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Static fiels doesn't load in django 1.11

I'm using django1.11 to build a web app.I have add required settings for static files in settings.py and all of static files was working fine. But I was trying to add 404 custom templates during that suddenly my static files stop loading.
Here's my settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'IGui', 'static'),
)
Here's my urls.py:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', home_url.index, name='home'),
url(r'^dockers/', views.DockerStuff.as_view(), name='docker-stuff'),
url(r'^user/', include(user_urls, namespace='users')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My directory tree:
-IGui
IGui
-static
--css
--js
Help me, please!
from django.shortcuts import render_to_response
from django.template import RequestContext
def handler404(request):
response = render_to_response('404.html', {},
context_instance=RequestContext(request))
response.status_code = 404
return response
def handler500(request):
response = render_to_response('500.html', {},
context_instance=RequestContext(request))
response.status_code = 500
return response
Add in you views.py the following two views, and just set up the templates 404.html and 500.html with what you want to display.
No custom code needs to be added to urls.py
Just turn Debug to True in settings.py will solve this issue.

500 Error Django file upload

I have been using this code to produce a file uploader and I can only get as far as getting the template to attempt an upload. I am wondering if I need to either configure Apache, add something to Django settings or install some more libraries maybe?
I have followed all the steps mentioned on that page, but please ask if you suspect I may have carried one or two of them out incorrectly.
Error
jssor.slider.js
Error INTERNAL SERVER ERROR
Settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_file_form',
'django_file_form.ajaxuploader',
'jfu',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.core.context_processors.static',
'django.contrib.auth.context_processors.auth',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
STATIC_ROOT = '/Users/Jonathan/Documents/django/bible/bible/static/jfu'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(os.path.dirname(__file__), 'static').replace('\\','/'),
)
views.py
from django.conf import settings
from django.core.urlresolvers import reverse
from django.views import generic
from django.views.decorators.http import require_POST
from jfu.http import upload_receive, UploadResponse, JFUResponse
#require_POST
def upload( request ):
# The assumption here is that jQuery File Upload
# has been configured to send files one at a time.
# If multiple files can be uploaded simulatenously,
# 'file' may be a list of files.
file = upload_receive( request )
instance = YOURMODEL( file = file )
instance.save()
basename = os.path.basename( instance.file.path )
file_dict = {
'name' : basename,
'size' : file.size,
'url': settings.MEDIA_URL + basename,
'thumbnailUrl': settings.MEDIA_URL + basename,
'deleteUrl': reverse('jfu_delete', kwargs = { 'pk': instance.pk }),
'deleteType': 'POST',
}
return UploadResponse( request, file_dict )
#require_POST
def upload_delete( request, pk ):
success = True
try:
instance = YOURMODEL.objects.get( pk = pk )
os.unlink( instance.file.path )
instance.delete()
except YOURMODEL.DoesNotExist:
success = False
return JFUResponse( request, success )
urls.py
from django.conf.urls import patterns, include, url
from bible import views
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'bible.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^verses/', views.index),
url(r'^search/', views.search),
url(r'^contact/', views.contact),
url(r'^profile/', views.profile),
url(r'^register', views.register),
url( r'upload/', views.upload, name = 'jfu_upload' ),
# You may optionally define a delete url as well
url( r'^delete/(?P<pk>\d+)$', views.upload_delete, name = 'jfu_delete' ),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
models.py
from django.db import models
from django.forms import ModelForm
from django.conf import settings
# Create your models here.
class Photo( models.Model ):
file = models.FileField( upload_to = settings.MEDIA_ROOT )
The issue was with the database. I think it was corrupted somehow and wouldn't talk with the application properly. Rebuilding it and running python manage.py migrate seemed to do the trick.

Loading static files into Django

I am trying to load my CSS, images, and javascript into my Django template using
{{ STATIC_URL }}
I am having a problem getting it to work. Here is the relevant code:
Url's.py:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
...
urlpatterns += staticfiles_urlpatterns()
Settings.py
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
MEDIA_URL = '/assets/'
STATIC_ROOT = os.path.realpath(os.path.join(PROJECT_ROOT, 'static'))
STATIC_URL = '/static/'
STATICFILES_DIRS = (
"/Users/Chris/project/static/",
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Stylesheet URl:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css">
If you need anymore information just ask, and thanks for your help!
UPDATE:
I have added the following things trying to fix the problem. But it still persists:
To the views where I'm trying to import the stylesheet:
'context_instance':RequestContext(request),
To the setting.py file:
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",
)
Here is my Installed App's if this helps:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'djblog',
)
My URLs.py file for the admin, and pointing to my other URL file:
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'blog.views.home', name='home'),
# url(r'^blog/', include('blog.foo.urls')),
url(r'^admin/', include(admin.site.urls)),
(r'^', include('djblog.urls')),
)
My main URL file:
from django.conf.urls.defaults import *
from views import *
from models import *
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = patterns('',
(r'^$', list),
(r'^archive/(?P<archive>\d{1,2})/$', list),
(r'^\d{4}/\d{1,2}/(?P<sl>.*)/$', detail),
(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/$', month),
(r'^(?P<year>\d{4})/$', year),
(r'^category/$', category),
(r'^category/(?P<category>.*)/$', one_category),
(r'^tag/$', tag),
(r'^tag/(?P<tag>.*)/$', one_tag),
)
urlpatterns += staticfiles_urlpatterns()
I have solved my own question. With the help of Kay Zhu
In my views I was passing the "context_instance" keyword argument to render_to_response, wrong.
Here is an example of the correct usage of context_instance:
def one_tag(request, tag):
#http://site_name/tag/tag_name
posts = Post.objects.order_by('-published').filter(tags__name=tag.lower())
return render_to_response('blog/one_tag.html',
{'posts':posts, 'tag':tag,},
context_instance=RequestContext(request))
This might also solve your similar problem. Add a file to your program directory with the following code:
def media_url(request):
from django.conf import settings
return {'media_url': settings.MEDIA_URL}
And this blog post has a lot of good information: http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/
Be wary though, its from 2006 :)

Filebrowser does not append slashes to files path when picking an image in django admin panel

Using python 2.7, django 1.4.1, filebrowser 3.5.0, grappelli 2.4.2, win7 x64
So heres my problem:
Im creating a object, and trying to attach an image to it:
Clicking on search:
Navigating through folders to get to my file, and picking it:
After i pick it, this is the path it returns:
Attaching model itself:
class EntryManager(models.Manager):
def active(self):
return super(EntryManager, self).get_query_set().filter(is_active=True)
class Services(models.Model):
name = models.CharField(max_length = 20, help_text = 'Nazwa oferowanej usługi', verbose_name='Usługa')
slug = models.SlugField(max_length=255, help_text = 'Odnośnik, generowany automatycznie na podstawie nazwy', unique=True,verbose_name='Odnośnik')
icon = FileBrowseField(verbose_name='Ikona', max_length=255, directory="images/", extensions=[".jpg",'.png','.gif'], blank=True, null=True,help_text = '.jpg, .png, .gif')
is_active = models.BooleanField(help_text='Zaznacz aby obiekt był widoczny dla użytkowników', default=False)
objects = EntryManager()
class Meta:
ordering = ['name']
verbose_name = "Usługę"
verbose_name_plural = "Usługi"
def __str__(self):
return self.name
def __unicode__(self):
return self.name
def get_absolute_url(self):
return '/uslugi/%s/' % self.slug
I have no idea where to search for a problem at the moment, could any1 help?
edit:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from filebrowser.sites import site
#when on dev, serve media files
from django.conf import settings
urlpatterns = patterns('',
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/filebrowser/', include(site.urls)),
url(r'^uslugi/?$', 'services.views.services'),
)
#when on dev, serve media files
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
and part of settings.py
import os
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__) + "../../")
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'site_media/media')
STATIC_ROOT = os.path.join(PROJECT_DIR, 'site_media/static')
ADMIN_MEDIA_PREFIX = os.path.join(PROJECT_DIR, 'site_media/admin_media')
INSTALLED_APPS = (
'grappelli',
'filebrowser',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'services'
)
After reading yours urls.py I need to show You Documentation:
In your url.py import the default FileBrowser site:
from filebrowser.sites import site
and add the following URL-patterns (before any admin-urls):
urlpatterns = patterns('',
url(r'^admin/filebrowser/', include(site.urls)),
)
So only differences between You and my new project are:
I'm using Linux Ubuntu x86 on VirtualBox undex Windows 7
I have /admin/file-browser BEFORE any admin-urls:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from filebrowser.sites import site
from django.conf.urls.static import static
from django.conf import settings
admin.autodiscover()
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + patterns('',
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/filebrowser/', include(site.urls)),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^', include('django.contrib.flatpages.urls')),
)

Categories

Resources