Django App template Loader, can't find app templates - django

I have the following two apps located in my virtualenv: backend backoffice.
The backoffice app has templates under:
backoffice/templates
So when I login into the Django shell, I can to do the following:
>>>from django.template.loaders.app_directories import Loader
>>> list(l.get_template_sources('index.html'))
[u'/var/www/venv2.7/lib/python2.7/site-packages/django/contrib/auth/templates/index.html', u'/var/www/venv2.7/lib/python2.7/site-packages/backoffice/templates/index.html', u'/var/www/venv2.7/lib/python2.7/site-packages/django/contrib/admin/templates/index.html']
So it seems the template is correctly found (l.load_template_source(('index.html') is also working).
However, when I access my home page via the browser I get an error:
TemplateDoesNotExist at /
Can someone help me solve the puzzle? What am I missing?
update: full trackback
Request Method: GET
Request URL: http://192.168.211.140/
Django Version: 1.5.1
Python Version: 2.7.6
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'backoffice',
'backend',
'django.contrib.admin')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/contrib/auth/templates/index.html (File does not exist)
/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/contrib/admin/templates/index.html (File does not exist)
Traceback:
File "/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "/var/www/backoffice/venv2.7/lib/python2.7/site-packages/backoffice/views.py" in start_page
177. return render(request, 'index.html', context)
File "/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/shortcuts/__init__.py" in render
53. return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
170. t = get_template(template_name)
File "/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/template/loader.py" in get_template
146. template, origin = find_template(template_name)
File "/var/www/backoffice/venv2.7/lib/python2.7/site-packages/django/template/loader.py" in find_template
139. raise TemplateDoesNotExist(name)
Exception Type: TemplateDoesNotExist at /
Exception Value: index.html

Ah, I want to cry, how can Django be so tricky ...
I just updated settings.INSTALLED_APPS:
# It was like this
INSTALLED_APPS = (
'django.contrib.auth',
...
'backoffice',
'backend',
'django.contrib.admin' #!!! NOT ALLOWED HERE
)
# This will workd
INSTALLED_APPS = (
'django.contrib.auth',
...
'django.contrib.admin' # ALLOWED HERE
'backoffice',
'backend',
)

The order of INSTALLED_APPS is important. However, a good standard practice to prevent collisions on template names when you use the app directory loader is to namespace your templates by the app name in its director structure, such that:
Your templates for app backoffice live in:
backoffice/templates/backoffice/
In implementation, you would be rendering the template "backoffice/index.html" which will never collide with a template in django.contrib.admin. This design pattern plays nice with pluggable apps. Should you ever release backoffice as a pluggable app, other users can override its templates in their main template directory by simply adding a backoffice directory.

Related

Why is django getting stuck on loading a template that doesn't exist?

I've made some changes to my website's theme and have come across an issue. My previous landing page was called home.html. It worked fine. I have since changed it, retired the old pages (moved them to another folder), and put a new set of pages in my template/app/ folder. The new landing page is index.html. I have changed it in urls.py, and in views.py. I come across this error, Django still wants to access or load main/home.html. I don't understand why, even after changing it to return a HttpResponse, it still wants to render a template? What's going on?
Environment:
Request Method: GET
Request URL: https://website.com
Django Version: 3.1.4
Python Version: 3.6.9
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main.apps.MainConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template loader postmortem
Django tried loading these templates, in this order:
Using engine django:
* django.template.loaders.app_directories.Loader: /usr/local/lib/python3.6/dist-packages/django/contrib/admin/templates/main/home.html (Source does not exist)
* django.template.loaders.app_directories.Loader: /usr/local/lib/python3.6/dist-packages/django/contrib/auth/templates/main/home.html (Source does not exist)
* django.template.loaders.app_directories.Loader: /var/www/app/main/templates/main/home.html (Source does not exist)
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/www/app/main/views.py", line 103, in homepage
return HttpResponse("well?")
File "/usr/local/lib/python3.6/dist-packages/django/shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/usr/local/lib/python3.6/dist-packages/django/template/loader.py", line 61, in render_to_string
template = get_template(template_name, using=using)
File "/usr/local/lib/python3.6/dist-packages/django/template/loader.py", line 19, in get_template
raise TemplateDoesNotExist(template_name, chain=chain)
Exception Type: TemplateDoesNotExist at /
Exception Value: main/home.html
ofcourse the source does not exist, i don't want it to. Why isn't it rendering the HTTPResponse? Even after I change the render to refer to template_name ="main/index.html" explicitly the issue persists.
Thanks to Boma Anjang. I just needed to restart the server.
systemctl reload apache2

How generate a pdf file with django-wkhtmltopdf on IIS 7.5 - 8

I use django-wkhtmltopdf to generate pdfs in my webapp, Works fine using the django integrate server, but when I use IIS 7.5 or 8 gives me this error: WindowsError [Error 6] The handle is invalid
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8006/blabla/pdf/10/
Django Version: 1.8.5
Python Version: 2.7.10
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'NuevoTicket',
'crispy_forms',
'wkhtmltopdf',
'ckeditor',
'ckeditor_uploader')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
164. response = response.render()
File "C:\Python27\lib\site-packages\django\template\response.py" in render
158. self.content = self.rendered_content
File "C:\Python27\lib\site-packages\wkhtmltopdf\views.py" in rendered_content
78. cmd_options=cmd_options
File "C:\Python27\lib\site-packages\wkhtmltopdf\utils.py" in render_pdf_from_template
159. cmd_options=cmd_options)
File "C:\Python27\lib\site-packages\wkhtmltopdf\utils.py" in convert_to_pdf
121. return wkhtmltopdf(pages=[filename], **cmd_options)
File "C:\Python27\lib\site-packages\wkhtmltopdf\utils.py" in wkhtmltopdf
109. return check_output(ck_args, **ck_kwargs)
File "C:\Python27\lib\subprocess.py" in check_output
566. process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "C:\Python27\lib\subprocess.py" in __init__
702. errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
File "C:\Python27\lib\subprocess.py" in _get_handles
857. errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
Exception Type: WindowsError at /blabla/pdf/10/
Exception Value: 6 The handle is invalid
Finally got it, thank's to n1b0r. I have to update the check_out method in python27/lib/subprocess.py like this
from:
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
to:
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
kwargs.pop('stderr', None)
process = Popen(stdout=PIPE, stderr=PIPE, stdin=PIPE, *popenargs, **kwargs)
That make it works in IIS but gives an error if use the django integrate server.
I used to have the same problem. Add the option quiet to the pdfkit and also try to modify the file configuration.py from pdfkit
options = {'quiet': ''}
pdfkit.from_file('in.html', 'out.pdf',options = options)
configuration.py
from this:
self.wkhtmltopdf = subprocess.Popen(['where','wkhtmltopdf'],stdout=subprocess.PIPE).communicate()[0].strip()
to:
self.wkhtmltopdf = subprocess.Popen(['which','wkhtmltopdf'],stdin=subprocess.PIPE,stderr=subprocess.PIPE, stdout=subprocess.PIPE).communicate()[0].strip()

<Model> matching query does not exist

I've learned python django since three days ago .
I wanted to remove an field from model, so I put the '#' front of that field.
Then I started the server again, but it gave me such an error message
'Userprofile matching query does not exist' (Userprofile is the model which I made.)
How can I solve this problem. I'm just a totally new to django, so even it's not easy to question my problem. If the clue is not enough, please tell me what other information is need.
p.s here is the total error message.
Environment:
Request Method: GET
Request URL: h ttp://localhost:8000/
Django Version: 1.6.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'admin_tools',
'admin_tools.theming',
'admin_tools.menu',
'admin_tools.dashboard',
'django.contrib.admin',
'south',
'autocomplete_light',
'djcelery',
'asap_web',
'facebook',
'venue',
'notification',
'study',
'general',
'member',
'advertise')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/jaehoon/PycharmProjects/studysearch/asap_web/__init__.py" in __call__
89. return main()
File "/home/jaehoon/PycharmProjects/studysearch/asap_web/__init__.py" in main
25. return process_request()
File "/home/jaehoon/PycharmProjects/studysearch/asap_web/__init__.py" in process_request
53. return _call_proper_request_processor()
File "/home/jaehoon/PycharmProjects/studysearch/asap_web/__init__.py" in _call_proper_request_processor
77. return getattr(self, method_name)(request, *self.args, **kwargs)
File "/home/jaehoon/PycharmProjects/studysearch/general/views.py" in process_get_request
19. if user.is_authenticated() and user.get_profile().is_required_more_info:
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py" in get_profile
441. self._state.db).get(user__id__exact=self.id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in get
307. self.model._meta.object_name)
Exception Type: DoesNotExist at /
Exception Value: UserProfile matching query does not exist.
The exception is DoesNotExist which is thrown when you use get to retrieve single instance but it does not exist. In your process_get_request view:
user.get_profile().is_required_more_info
is throwing this exception because there is no profile created for this user. Note that user.get_profile() is deprecated since django 1.5 and you should use OneToOne field or custom user model instead, from docs:
get_profile() Deprecated in Django 1.5: Deprecated since version 1.5:
With the introduction of custom User models, the use of
AUTH_PROFILE_MODULE to define a single profile model is no longer
supported. See the Django 1.5 release notes for more information.

Django Type Error - render to string got multiple values for keyword argument context_instance

I'm new in django and I collect all the static and templates from the admin site to customize. Now I'm trying to render a queryset to the change_list.html from the admin site.
view.py
def person_list(request):
if request.method == 'GET':
qs = Person.objects.all()
return render(request, 'admin/change_list.html', {'app_label': 'clients'}, {'results_list':qs})
else:
return render(request, 'admin/change_list.html')
And I'm getting this type error:
render_to_string() got multiple values for keyword argument 'context_instance'
Here is the full traceback:
Environment:
Request Method: GET
Request URL: http://localhost:8000/clients/persons/
Django Version: 1.5.1
Python Version: 2.7.4
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'equipment',
'workers',
'clients',
'rents',
'bills',
'pays')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/home/facundo/dev/BLPServicios/blpservicios/clients/views.py" in persona_list
9. return render(request, 'admin/change_list.html', {'app_label': 'clients'}, {'results_list':qs})
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py" in render
53. return HttpResponse(loader.render_to_string(*args, **kwargs),
Exception Type: TypeError at /clients/persons/
Exception Value: render_to_string() got multiple values for keyword argument 'context_instance'
Can you help me solve this? Thanks!
Try send values in one dictionary
{'app_label': 'clients', 'results_list':qs}
i think you are using the admin module to do something it can't... what are you trying to do?
i guess you'd better try to do it without the admin. often customizing it is more painful than implementing the code yourself, because of its complexity!
in particular, the {% result_list cl %} tag you see in the admin tamplate change_list.html (line 91) is not a template varible (that you are trying to pass in the context) but a template custom tag! whatever you want to do, this is the wrong path ;)

Just upgraded to Django 1.4 and getting error with messages

I just upgraded to Django 1.4 and it has broken a couple things including messaging.
Here's the error I get when trying to change a avatar:
'User' object has no attribute 'message_set'
Exception Location: /Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/utils/functional.py in inner, line 185
Traceback:
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
20. return view_func(request, *args, **kwargs)
File "/Users/nb/Desktop/spicestore/apps/avatar/views.py" in change
76. request.user.message_set.create(
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/utils/functional.py" in inner
185. return func(self._wrapped, *args)
Exception Type: AttributeError at /avatar/change/
Exception Value: 'User' object has no attribute 'message_set'
Also, messaging no longer works on the site. What are the changes in Django 1.4 that could be causing this and has anyone overcome a similar issue?
Django introduced a messages app in 1.2 (release notes), and deprecated the old user messages API.
In Django 1.4, the old message_set API has been removed completely, so you'll have to update your code. If you follow the messages docs, you should find it pretty straight forward.
Add
from django.contrib import messages
And then
def foo(request):
messages.add_message(request, messages.INFO, "Your message.")
What is in your INSTALLED_APPS in your settings.py?
Do you have 'django.contrib.messages', included there?
Something like:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
...
From Django 1.4 docs
To enable message functionality, in settings.py do the following:
Edit the MIDDLEWARE_CLASSES setting and make sure it contains
'django.contrib.messages.middleware.MessageMiddleware'
If you are using a storage backend that relies on sessions (the default), django.contrib.sessions.middleware.SessionMiddleware must be enabled and appear before MessageMiddleware in your MIDDLEWARE_CLASSES.
Edit the TEMPLATE_CONTEXT_PROCESSORS setting and make sure it contains
'django.contrib.messages.context_processors.messages'
Add 'django.contrib.messages' to your INSTALLED_APPS setting
As far as django-avatar is concerned. Use the master files found here: https://github.com/chadpaulson/django-avatar/tree/master/avatar