Django Tutorial - TemplateDoesNotExist at /polls/ - python

I have tried to get this to work a million times. I have lef it alone for a week and come back. I have Googled and read every post pertaining to this. I have let insecure morons belittle in messages groups without ever finding the answer. I just want this to work. When I am following along in part three of the the Django tutorial, I get to the part where you make the template for the index page, and when I go to check it in the browser, it comes up with TemplateDoesNotExist at /polls/. I have checked file ownership, moved it all around, always changing the TEMPLATES_DIR in setting.py. I have pipe'd the contents of the file to cat to make sure it works. I have scarificed animals to strange Gods to get this to work. I turn to you now. I am sure it is the stupidest thing ever, I have very little doubt about this. I just want it to work.
I am not sure what parts of the code/traceback you want/need here, let me know I will post them. I am doing this on Ubuntu 10.10
EDIT
From settings.py:
TEMPLATE_DIRS = (
"home/kevin/first/tutorial/temps"
)
This used to live in ~, but I moved into the project folder thinking it would help.
Structure(leaving out all complied python files):
~/first/tutorial/:
__init__.py,
manage.py,
polls,
settings.py,
temps,
tut.db,
urls.py
temps:
index.html
polls:
admin.py,
__init__.py,
models.py,
tests.py,
views.py,

>>> TEMPLATE_DIRS = ( "home/kevin/first/tutorial/temps" )
>>> print TEMPLATE_DIRS
home/kevin/first/tutorial/temps
>>> type(TEMPLATE_DIRS)
<type 'str'>
This is a string, not a tuple.
TEMPLATE_DIRS = ( "home/kevin/first/tutorial/temps", )
That is a tuple. A little bit of a Python gotcha.
Furthermore, use an absolute path rather than a relative path.

First off, and this might not be relevant to your problem, but it's good practice to not use absolute paths in your files. I always have the following in my settings.py:
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, 'templates'),
)
You should always have a comma at the end of an element in your tuple, even if it is the only one or the last one, so that Python actually considers it to be a tuple and not evaluate to any other type.
You should also make sure that your TEMPLATE_LOADERS setting contains or looks like this:
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
If that doesn't fix it (you should still keep the above in regardless), the problem is most likely related to the template you're rendering to. Confirm that the string of the template you're using in the view corresponds correctly to the relative path of the template within your templates directory. In other words, if the template string is 'polls/index.html' in your view, ensure that the file is actually located at templates/polls/index.html.

What I've used in my settings.py configuration file was:
"TEMPLATE_DIRS = (
'/path/to/folder/Python-templates',
)"
And it worked. What I guess (and correct me if I'm wrong) is that the example in the django tutorial is making reference to the exact location of the template within the templates folder, which is polls. Thus, in the example found in this tutorial, the polls/index.html path to file is saying "the index.html file in the polls folder that is already in the template folder specified in settings.py".

This happened to me because I skipped to part three (I wanted to learn about templates) and I forgot to add add the PollsConfig to INSTALLED_APPS
Your mysite/settings.py should look this this:
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
After I did this change, the templates were all found.
This is a bit confusing because you don't have to do this to make your views work. But templates definitely won't load if your app's config is not in INSTALLED_APPS.

Some things to check:
Do you use an absolute path to specify the template directory in settings.py?
Did you put the template directly into the TEMPLATE_DIR directory, or did you make a polls subfolder to put the template in?

I had the same issue as you described, doing the third part of the Django tutorial throws TemplateDoesNotExist.
Restarting the server solved it for me (did not change any configurations). Hope that helps...

Related

routes on error functionality not working in web2py

i am trying to present a custom error to the end user , but these custom routes are not working and i am still being shown default ticker number, since exposing ticker numbers pose security issues, what am i missing? need help in this thanks in advance ,
Also i have these routes in routes.py in project level directory adjacent to web2py.py
routes_onerror = [
('gms/404', '/gms/static/404.html'),
('gms/500', '/gms/static/500.html'),
('gms/408', '/gms/static/404.html'),
('gms/400', '/gms/static/404.html'),
('super/*', '/super/static/404.html'),
(r'*/*', r'/gms/static/404.html'),
]

?: (urls.E006) The STATIC_URL setting must end with a slash

I was trying to migrate my new schema for my database in django when I got this error:
AttributeError: 'PosixPath' object has no attribute 'startswith'
I looked online and I saw that if you wrap your paths with str(), the error goes away.
But then I got this error:
?: (urls.E006) The STATIC_URL setting must end with a slash.
I tried doing the obvious thing and changing STATIC_URL = BASE_DIR.parent / "svelte" / "public"(what I think was causing the error) That didn't work, so I tried STATIC_URL = BASE_DIR.parent / "svelte" / "public" /. That also didn't work, so know I need help.

Dealing with versioning using URLPathVersioning in Django 2

I've been having some troubles lately trying to set my REST API to use path versioning.
I have the code in my_app/urls.py with:
def ping():
return "pong"
API_PREFIX = r'^(?P<version>(v1))'
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(f'^{API_PREFIX}/ping/$', get_json(ping))) # assume that get_json returns the right thing
]
I added this lines to settings.py in the same directory:
REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning'
'DEFAULT_VERSION': 'v1',
'ALLOWED_VERSIONS': ('v1',),
}
This doesn't work if I do a GET localhost:8000/v1/ping/. Is a f string able to include regex syntax or is the problem somewhere else? I tried fr'^{(API_PREFIX}}/ping/$' and that didn't work either.
Bonus question: In the ping function, how can I access and check the version number passed in the path (1 in that case, but will change over time)?
I found out the problem. This paragraph from the docs outlines the problem I was facing;
Using unnamed regular expression groups¶ As well as the named group
syntax, e.g. (?P[0-9]{4}), you can also use the shorter unnamed
group, e.g. ([0-9]{4}).
This usage isn’t particularly recommended as it makes it easier to
accidentally introduce errors between the intended meaning of a match
and the arguments of the view.
> In either case, using only one style within a given regex is
recommended. When both styles are mixed, any unnamed groups are
ignored and only named groups are passed to the view function.

How to get all available values for FilePathField in Django 1.5?

I have a model, which has FilePathField attribute. It has a folder to search, regular expression to match and other needed parameters.
I need a standard method to get the list of all available for this FilePathField paths. Or it does not exist?
No, there isn't one. You can write your own using path, match and recursive. However, this is how the admin widget form for FilePathField gets all the paths - https://github.com/django/django/blob/master/django/forms/fields.py#L999
from django.forms.fields import FilePathField
a = FilePathField(path='/path')
print a.choices

Django i18n: Common causes for translations not appearing

I am making a multilingual Django website. I created a messages file, populated and compiled it. I checked the site (the admin in this case,) in my wanted language (Hebrew) and most phrases appear in Hebrew like they should, but some don't. I checked the source and these still appear as _('Whatever') like they should, also they are translated on the messages file, and yes, I remembered to do compilemessages.
What are some common causes for translations not to appear like that?
Maybe the translated strings are marked as fuzzy?
Just got hit by one. I had the locale/ directory in the root of my project, but by default Django looks for translations in the INSTALLED_APPS directories, and in the default translations. So it didn't find the translations I added. But some of my strings were in the default translations that come with Django (eg "Search") so a few strings were translated, which confused me.
To add the directory where my translations were to the list of places that Django will look for translations, I had to set the LOCALE_PATHS setting. So in my case, where the locale/ directory and settings.py were both in the root of the django project I could put the following in settings.py:
from os import path
LOCALE_PATHS = (
path.join(path.abspath(path.dirname(__file__)), 'locale'),
)
I'm trying to provide a complete check list:
In settings.py, are USE_I18N, USE_L10N, LANGUAGE_CODE, and LOCALE_PATHS set properly?
See this list for all allowed values of language identifiers. Note that Simplified Chinese is specified by zh-hans, not zh-cn.
In settings.py, is django.middleware.locale.LocaleMiddleware included in MIDDLEWARE in correct order?
Have you (re)run django-admin makemessages -l <locale-name> with the correct local name, from the correct place?
You can see an incomplete list of allowed locale name by running ls your/path/to/python/site-packages/django/conf/locale/ on your machine, or by taking a look at the source code
Note that you have to use _ rather than - here. For example, to specify simplified Chinese, execute django-admin makemessages -l zh_Hans, not zh_CN or zh_hans or zh-Hans or anything else.
Have you removed all fuzzy tags in your PO file(s)?
Have you (re)compiled the OP file(s) with django-admin compilemessages?
Have you restarted the web server?
Additional notes:
If some of your translation is overridden by Django's default translation, use contextual markers to bypass it. For example,
models.py
first_name = models.CharField(
pgettext_lazy('override default', 'first name'),
max_length=30
)
last_name = models.CharField(
pgettext_lazy('override default', 'last name'),
max_length=150
)
django.po
#: models.py:51
msgctxt "override default"
msgid "first name"
msgstr "姓"
#: models.py:55
msgctxt "override default"
msgid "last name"
msgstr "名"
and you'll see 姓, 名 instead of the default 姓氏, 名字.
I was having this problem with my project right now. I had the variable LANGUAGES on settings.py set this way:
LANGUAGES = (
('en', _('English')),
('pt-br', _('Brazilian Portuguese')),
)
And a folder structure with a locale folder, and a subfolder pt-br inside. Turns out that my translations weren't loading. The LANGUAGES variable follows the pt-br pattern, and the folders must be on pt_BR pattern. At least that's the only way it's working here!
Hi just attach some fixes I had to do in the past:
Restart the webserver!
In the setting file
- USE_I18N = True is needed
django.middleware.locale.LocaleMiddleware among middleware modules (but this is not your case for sure as long as Django will not care about your local at all)
django.core.context_processors.i18n among TEMPLATE_CONTEXT_PROCESSORS
for sure I had other issues related to translations but I don't remember them all... hope this can help!
A possible cause is Lazy Translation.
In example, in views.py you should use ugettext:
from django.utils.translation import ugettext as _
But in models.py, you should use ugettext_lazy:
from django.utils.translation import ugettext_lazy as _
Another cause can be a wrong directory structure.
Read well the manage command's error message about which directory to create before running the makemassages command for the app translation. (It must be locale for an app, not conf/locale.) Note that the management commands work fine even with the wrong directory structure.
I noticed that when I had % in my text, the translated text was not being used. There may be other characters that can cause this problem. I fixed the problem by escaping the % as %%.
My answer here, all my translations were working except for 2 DateFields that I was using in a ModelForm.
Turns out that I had a widget in my forms.py that was not working well with the translations.
I just removed it for now so I can enjoy Xmas =D

Categories