I am trying to load a template from a nested directory in django but keep getting a improperly configured no pattern match error. I've attempted all combinations of folder names but the error keeps on continuing, I'm scratching my head with this one, any help? here are my files:
view.py
from django.http import HttpResponse
from django.template import loader
def index():
curTemplate = loader.get_template('/droneMapper/index.html')
return HttpResponse(curTemplate.render())
settings.py
BASE_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)
TEMPLATE_DIRS = (os.path.abspath(os.path.join(BASE_DIR, 'templates')),)
the file strcture is:
root
-app
-templates
-app
-setting
I simply use this small code:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),)
works fine for me.
Related
My Django app is unable to see MEDIA directory. When I run one of my views I need to open a file. The scenario is to:
take a record with requested id from data base
get the file path to a file
send the file to external server for OCR purposes
urls.py
from django.conf.urls.static import static
urlpatterns = [
#my urls
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
models.py
from django.db import models
from django.contrib.auth.models import User
class Homework( models.Model):
title = models.CharField(max_length = 200, default = None)
image = models.FileField(upload_to='user_scans/')
author = models.ForeignKey(User, default=None, on_delete = models.CASCADE)
latex = models.TextField(default = "No LaTeX Here")
settings.py:
from pathlib import Path
from django.conf.urls.static import static
BASE_DIR = Path(__file__).resolve().parent.parent
...
DEBUG = True
...
STATIC_ROOT = BASE_DIR / 'static'
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = "/media/"
views.py
import requests
import json
from django.shortcuts import render, get_object_or_404
from .models import Homework
def create_homework(request):
if request.method == 'GET':
#some GET stuff
if request.method == 'POST':
homework = Homework()
homework.title = title
homework.image = image
homework.author = author
homework.save()
id = homework.id
json_to_mathsnip(id)
....
def json_to_mathsnip(id):
homework = get_object_or_404(Homework, pk=id)
f = open(homework.image.url, "rb")
...
some later stuff
...
Unfortunately I'm constantly running into an error:
FileNotFoundError at /homework/new
[Errno 2] No such file or directory: '/media/user_scans/kwa.png'
My main concern is I can access file from localhost:8000/media/user_scans/kwa.png
and from admin panel. Requested file is saved properly:
Also settings.py configuration seems to be in tact. What might be the issue?
(env) $ pip freeze
asgiref==3.5.0
backports.zoneinfo==0.2.1
certifi==2021.10.8
charset-normalizer==2.0.12
Django==4.0.1
idna==3.3
Pillow==9.0.0
psycopg2-binary==2.9.3
requests==2.27.1
sqlparse==0.4.2
urllib3==1.26.9
This may not be the best way, but I tried it and it works. The bottom line is that when using the open() function with a relative path, such as /media/user_scans/kwa.png, then that file must be in the same directory as where the function is called. You could just find the absolute path of your image files in your computer, then append the filename to that and it will work, or you can do what I have below.
import requests
import json
from django.shortcuts import render, get_object_or_404
from .models import Homework
# ADD THESE
import os
from pathlib import Path
def create_homework(request):
if request.method == 'GET':
#some GET stuff
if request.method == 'POST':
homework = Homework()
homework.title = title
homework.image = image
homework.author = author
homework.save()
id = homework.id
json_to_mathsnip(id)
....
def json_to_mathsnip(id):
homework = get_object_or_404(Homework, pk=id)
# ADD THESE
BASE_DIR = Path(__file__).resolve().parent.parent
path_to_image_file = str(BASE_DIR) + homework.image.url
f = open(path_to_image_file, "rb")
...
some later stuff
...
When you show an image in Django, or you access its url, it is a relative path, but the root is the url root, localhost:8000/, and the image url is appended to that, and Django manages to find the file (how exactly, I don't know). But the image file is in your computer, and that is what you want to open.
I am not able to render any html pages in Django 1.7. My 'index.html' is in 'project/seatalloc/templates/index.html' and my view.py in project/seatalloc/views.py looks like:
def index(request):
return render(request, 'index.html', dirs=('templates',))
project/project/settings.py has templates dirs set:
TEMPLATE_DIRS = (
'/Users/Palak/Desktop/academics/sem3/cs251/lab11/project/seatalloc/templates',
)
urls.py:
urlpatterns = patterns('',
url(r'^seatalloc/', include('seatalloc.urls')),
url(r'^admin/', include(admin.site.urls)),
)
I have tried to follow the documentation strictly, yet can't figure out if Django detects the file, why am I getting TemplateDoesNotExist at /seatalloc/ error. I am new to Django, could someone please help.
If - as in your case - you get a TemplateDoesNotExist error and the debug page states "File exists" next to the template in question this usually (always?) means this template refers to another template that can't be found.
In your case, index.html contains a statement ({% extends %}, {% include %}, ... ) referring to another template Django cannot find. Unfortunately, as of Django 1.8.3, the debug page always names the base template, not the one Django can't find.
Try like this,
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates/'),
)
First of all don't use static path (fixed path) in template dirs in settings.py, use:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = (
BASE_DIR +'/Templates',
)
And template directory should be in project directory i.e in which manage.py file exists.
And in view.py use render_to_response instead of just render.
return render_to_response("index.html")
Until not long ago, I used to do this in many places in my Django app:
from MyApp import settings
This required that I put settings inside my MyApp directory. I realized that is wrong, so I started using:
from django.conf import settings
But now I can't figure out how to find the path to settings.py from withing my code. Earlier I could use settings.__file__.
As a workaround I defined inside settings.py:
PATHTOSELF = os.path.dirname(__file__)
Any ideas how to find the path to settings.py?
Try This:
import os
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
This should work for you:
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
Place it on top inside of your settings.py. You can then import PROJECT_ROOT at any point in your code like this:
from myapp.settings import PROJECT_ROOT
I am making a Django Project, A Business Directory.
Here I have used ABSOULATE PATHS for Template rendering,
I thnk this might create problem in future.
Please look into my codes and Suggest me how to solve this problem so that it does not create any problem in future.
Please help
my models.py is::
from django.db import models
class Directory(models.Model):
Bussiness_name = models.CharField(max_length=300)
Description = models.CharField(max_length=900)
Number = models.CharField(max_length=100)
Web_url = models.CharField(max_length=800)
Catogory = models.CharField(max_length=200)
def __unicode__(self):
return self.Bussiness_name
class Adress(models.Model):
directory = models.ForeignKey(Directory)
adress_name = models.CharField(max_length=300)
def __unicode__(self):
return self.adress_name
class Photos(models.Model):
directory = models.ForeignKey(Directory)
Photo_path = models.CharField(max_length=100)
Photo_name = models.CharField(max_length=100)
def __unicode__(self):
return self.Photo_name
My view.py is ::
# Create your views here.
from django.http import HttpResponse
from crawlerapp.models import Directory
from crawlerapp.models import Adress
from crawlerapp.models import Photos
from django.template import Context, loader
from django.shortcuts import render
def index(request):
Directory_list = Directory.objects.all()
t=loader.get_template('C:/Python27/django/crawler/templates/crawlertemplates/index.html')
c = Context({'Directory_list': Directory_list,})
return HttpResponse(t.render(c))
def contactus(request):
Directory_list = Directory.objects.all()
t=loader.get_template('C:/Python27/django/crawler/templates/crawlertemplates/contactus.html')
c = Context({'Directory_list': Directory_list,})
return HttpResponse(t.render(c))
def search(request):
if 'what' in request.GET and request.GET['what']:
what = request.GET['what']
crawlerapp = Directory.objects.filter(Catogory__icontains=what)
return render(request, 'C:/Python27/django/crawler/templates/crawlertemplates/search.html',
{'crawlerapp': crawlerapp, 'query': what})
elif 'who' in request.GET and request.GET['who']:
who = request.GET['who']
crawlerapp = Directory.objects.filter(Bussiness_name__icontains=who)
return render(request, 'C:/Python27/django/crawler/templates/crawlertemplates/search.html',
{'crawlerapp': crawlerapp, 'query': who})
else:
message = 'You submitted an empty form.'
return HttpResponse(message)
And my urls.py is::
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'^$', 'crawler.views.home', name='home'),
# url(r'^crawler/', include('crawler.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)),
url(r'^crawlerapp/$', 'crawlerapp.views.index'),
url(r'^crawlerapp/contactus/$', 'crawlerapp.views.contactus'),
url(r'^crawlerapp/search/$', 'crawlerapp.views.search'),
)
I have 3 html pages INDEX, CONTACTUS, and SEARCH.
Please suggest an alternative of Absolute path so that it create no errors if I someone else clones it from GITHUB and try to run it.
Please help to solve this.
You should list you're template directories in your setting.py files, in the TEMPLATE_DIRS list.
Whether you do that or not, you should dynamically generate the absolute path by using the os.path module's function.
os.path.abspath(__file__)
will return the absolute path to the file it's called in.
os.path.dirname('some/path')
will return the path to the last directory in 'some/Path'
By combining them you can get absolute pathes which will remain accurate on different systems, eg
os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
will return an absolute path to the directory one level above the one containing the current file.
Go read the docs for the os.path module. You'll probably need to use os.path.join as well.
Have you considered reading the Django tutorial?.
Don't forget to set TEMPLATE_DIRS in your settings.py file, a good tip for doing so can be found on another answer; Django template Path
In your project settings.py file:
Add this at the top
import os.path
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
Then to set template path do this:
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, "templates"),
)
With this you going to be in the obligation in a future to recheck your all files to change the path in case if you change directories so: in you settings.py file define:
import os.path
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__),'templates').replace('\\','/'),
'/path/to/my/project/'
'/path/to/my/project/template/', # for the apps
)
Where templates/ is the directory for your templates.
I am new to Django and cannot figure out what the path to my templates is supposed to look like. My project's directory tree looks like this:
blog
blog/blog
blog/blog/__init__.pyc
blog/blog/wsgi.pyc
blog/blog/urls.py
blog/blog/urls.pyc
blog/blog/wsgi.py
blog/blog/__init__.py
blog/blog/settings.py
blog/blog/settings.pyc
blog/home
blog/home/views.py
blog/home/templates
blog/home/templates/home
blog/home/templates/home/main.html
blog/home/__init__.pyc
blog/home/urls.py
blog/home/urls.pyc
blog/home/models.py
blog/home/tests.py
blog/home/__init__.py
blog/home/views.pyc
blog/manage.py
Here is my view (from blog/home/view.py):
from django.shortcuts import render_to_response
def home(request):
return render_to_response("home/main.html", {"name" : "maxwell"})
A redacted copy of my settings.py file can be found here: http://pastebin.com/UMTepK9j
And finally, here is the error I get when I browse to 127.0.0.1:8000:
TemplateDoesNotExist at /home/main.html
Can anyone tell me what the path ought to look like in my call to render_to_response?
The TEMPLATE_DIRS in your settings.py should point to the template folder.
Should be something like this:
TEMPLATE_DIRS = (
'../home/templates'
)
That should work.
Note: There you're using relative paths which is not recommended. You should have something like this in your settings.py:
import os
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))
...
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, '../home/templates/'),
)
Also, you're calling render_to_response without passing it a RequestContext. With this, your templates will lack of some variables important for your project like user. It's better to call it this way:
return render_to_response(
"home/main.html",
context_instance=RequestContext(
request,
{'name':'maxwell'}
)
)