How do I make Django's DATETIME_FORMAT active? - django

Where should DATETIME_FORMAT be placed for it to have effect
on the display of date-time in the Django admin site
(Django’s automatic admin interface)?
Documentation for DATETIME_FORMAT, on page
http://docs.djangoproject.com/en/1.0/ref/settings/, says:
"The default formatting to use for datetime fields on
Django admin change-list pages -- and, possibly, by
other parts of the system."
Update 1: DATETIME_FORMAT is broken (the value of it is
ignored), despite the documentation. Many years ago it
worked, but since then the Django implementations have been
broken wrt. this feature. It seems the Django community
can't decide how to fix it (but in the meantime I think they
should remove DATETIME_FORMAT from the documentation or add
a note about this problem to it).
I have put these lines into file "settings.py" of the
website/project (not the app), but it does not seem to have
any effect (after restarting the development server):
DATETIME_FORMAT = 'Y-m-d H:i:sO'
DATE_FORMAT = 'Y-m-d'
As an example "June 29, 2009, 7:30 p.m." is displayed when
using Django admin site.
Django version is 1.0.2 final and Python version is 2.6.2
(64 bit). Platform: Windows XP 64 bit.
Stack Overflow question European date input in Django Admin seems to be about the exact opposite problem (and thus an apparent
contradiction).
The full path to file "settings.py" is
"D:\dproj\MSQall\website\GoogleCodeHost\settings.py". I now
start the development server this way (in a Windows command
line window):
cd D:\dproj\MSQall\website\GoogleCodeHost
set DJANGO_SETTINGS_MODULE=GoogleCodeHost.settings
python manage.py runserver 6800
There is no difference. Besides these are positively read
from file "settings.py":
DATABASE_NAME
INSTALLED_APPS
TEMPLATE_DIRS
MIDDLEWARE_CLASSES
"django-admin.py startproject XYZ" does not create file
"settings.py" containing DATETIME_FORMAT or DATE_FORMAT.
Perhaps there is a reason for that?
The sequence "d:", "cd D:\dproj\MSQall\website\GoogleCodeHost",
"python manage.py
shell", "from django.conf import settings",
"settings.DATE_FORMAT", "settings.DATETIME_FORMAT" outputs
(as expected):
'Y-m-d H:i:sO'
'Y-m-d'
So the content of file "settings.py" is being read, but does
not take effect in the Django Admin interface.

With:
USE_L10N = False
DATE_TIME takes effect, since the localization of l10n overrides DATETIME_FORMAT and DATE_FORMAT as documented at: https://docs.djangoproject.com/en/1.9/ref/settings/#date-format

As Ciro Santilli told, localization format overrides DATETIME_FORMAT in settings when USE_L10N = True. But you can still override DATETIME_FORMAT and other date/time formats by creating custom format files as described in Django documentation.
See detailed answer here.
You can override DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT and other date/time formats when USE_L10N = True by creating custom format files as described in Django documentation.
In summary:
Set FORMAT_MODULE_PATH = 'yourproject.formats' in settings.py
Create directory structure yourproject/formats/en (replacing en with the corresponding ISO 639-1 locale code if you are using other locale than English) and add __init__.py files to all directories to make it a valid Python module
Add formats.py to the leaf directory, containing the format definitions you want to override, e.g. DATE_FORMAT = 'j. F Y'.
Example from an actual project here.

This will solve the particular problem that is not possible
with DATETIME_FORMAT (as it is ignored in the current Django
implementations despite the documentation), is dirty too and
is similar to ayaz's answer (less global - will only affect
the admin site list view):
Right after the line
(date_format, datetime_format,time_format) = get_date_formats()
in file (Django is usually in folder Lib/site-packages in
the Python installation)
django/contrib/admin/templatetags/admin_list.py
overwrite the value of datetime_format (for a
models.DateTimeField in the model):
datetime_format = 'Y-m-d H:i:sO'
And for date-only fields:
date_format = 'Y-m-d'
Restart of the web-server (e.g. development server) or
logging out of the admin interface is NOT necessary for
this change to take effect. A simple refresh in the web-browser
is all what is required.

The two setting directives should be defined in settings.py. Could you ensure that the same settings.py that you are editing is being read when you start the development server?
You could always drop to the Python interactive shell by running python manage.py shell, and run these commands to ensure whether the date/time format values are getting through fine:
from django.conf import settings
settings.DATE_FORMAT
settings.DATETIME_FORMAT
Ok, I forgot to look it up, but ticket #2203 deals with this. Unfortunately, the ticket remains in pending state.
I remember that for a project that used a certain trunk revision of the 0.97 branch of Django, I worked around that by overwriting the date_format and datetime_format values in the get_date_formats() function inside django/utils/translation/trans_real.py. It was dirty, but I had already been using a custom Django of sorts for that project, so didn't see anything going wrong in hacking it trifle more.

Related

Python installation doesn't support type of template loading

I've installed Aldryn-boilerplates, using Configuration block's advices from github (https://github.com/aldryn/aldryn-boilerplates#configuration).
But when I make python manage.py runserver I recieve a message:
/home/stp/env/local/lib/python2.7/site-packages/django/template/loader.py:110: UserWarning: Your TEMPLATE_LOADERS setting includes'aldryn_boilerplates.template_loaders.AppDirectoriesLoader', but your Python installation doesn't support that type of template loading. Consider removing that line from TEMPLATE_LOADERS.
warnings.warn("Your TEMPLATE_LOADERS setting includes %r, but your Python installation doesn't support that type of template loading. Consider removing that line from TEMPLATE_LOADERS." % loader)
The web page loads normally (without any template or style).
Also a question, where to put line ALDRYN_BOILERPLATE_NAME = 'bootstrap3'? I've placed it in the bottom of my project's settings.py file.
Anyone knows how to fix that? Or maybe there are another framework with much more detailed description about installation and configuration, which fits for beginners?
I got the some error with django 1.8 and a custom template loader. I had overridden the Loader class out of django.templates.loaders.base. To get rid of this error I also had to the set the class variable is_usable to true
class Myloader(Loader):
is_usable = True
So maybe you can solve your issue with subclassing the 'aldryn_boilerplates.template_loaders.AppDirectoriesLoader' and only change the class variable as shown above.
You have placed the ALDRYN_BOILERPLATE_NAME = 'bootstrap3' at the right place. Please mention the versions of python and django-cms you are using. If you want to try another blogging platform for python, then http://mezzanine.jupo.org/ is helpful for beginners, because it's very easy to setup.

Why are some strings in Django .po translated while others not?

This is the first time I used Django localization.
I generated the .po files with makemessages and randomly select a
few strings to fill in the translations, just to check if
localization works.
Then I generate the .mo file with
compilemessages.
I go to the web page and only see a string
'Username' translated, most other strings don't get the translated
version displayed.
What is going on here?
EDIT:
I found out why 'Username' is translated, it used the default translation in Django, but why Django didn't use my mo file is beyond me. I followed all the instructions in i18n doc.
I set the LOCALE_PATHS variable in settings.py to the path for my localization files.
I tried different LANGUAGE_CODE settings 'zh-cn', 'zh_CN'(both the setting variable and the directory name).
I tried msgunfmt django.mo, the file is valid.
There are some lines close to the beginning of po file:
#, fuzzy
msgid ""
msgstr ""
I believe this is normal.
I finally got it working after hours of trial and error.
I change my LOCALE_PATHS from:
LOCALE_PATHS = ("/path/to/locale/");
to:
LOCALE_PATHS = ("", "/path/to/locale/");
And it works right away. Maybe it is a bug with Django 1.5 (which I am using), or maybe I configured something wrong.
Anyway, hope this helps someone, and save you hours of time.
=========EDIT===========
As pointed out by #J.C.Leitão, you have to add comma to make the variable a tuple.
It was a rookie mistake of mine. But I think Django could be more friendly to developers if a single string is recognized, too.

django-lockdown password prompt not displayed

I'm having the same problem as this question. However, on my local machine, the password prompt is displayed, but when I push to my development server on Openshift, the password prompt is not displayed. Instead, only this is displayed:
Coming soon...
This is not yet available to the public.
Again, as the linked question states, it seems like the form context variable is not passed to the template. I have not changed anything in lockdown. Furthermore, this used to work. I've gone through the history of my settings.py and no smoking gun. What's irritating is that this works on my local machine. Here's the lockdown related variables in my settings.py:
USE_LOCKDOWN = True
if USE_LOCKDOWN:
INSTALLED_APPS += ('lockdown',)
MIDDLEWARE_CLASSES += ('lockdown.middleware.LockdownMiddleware',)
LOCKDOWN_PASSWORD = ('mypassword')
LOCKDOWN_URL_EXCEPTIONS = (r'^/admin',)
LOCKDOWN_FORM = 'lockdown.forms.LockdownForm'
Found the problem.
When I had initially installed lockdown using pip on my local machine, pypi only had version 0.1.1, which uses LOCKDOWN_PASSWORD. In my settings.py, I used a string for the password, not a tuple. In the question I had linked to in my original post, the answers mentioned passing a tuple instead of string. I tried that, and that did not work.
When you push code onto OpenShift and don't specify the version in setup.py, it downloads the latest version of the package. In the latest version of lockdown, LOCKDOWN_PASSWORDS is used instead and that expects a tuple. I updated my settings.py file accordingly, and now a password prompt is displayed.

Error when trying to load Django custom filters into template

I've inherited a Django application that I need to modify using a custom template filter. I'm absolutely new to Django and am quite mystified by it. I thought I had followed the instructions exactly, and also followed all the advice from other posts on the subject, but I still get an error when I include the following line in my template:
{% load mlgb_custom_filters %}
My directory structure is as follows:
mysite (i.e. the project)
__init__.py
mlgb/ (i.e. the app)
__init__.py
templatetags/
__init__.py
mlgb_custom_filters.py
The code of mlgb_custom_filters.py is as follows:
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
#register.filter(name='fix_dashes')
#stringfilter
def fix_dashes( value ):
return value.replace( '--', 'DASH' )
if __name__ == "__main__":
testvar = fix_dashes( "ouch -- ow -- I hate django" )
print testvar
As you can see, I've added a 'name = main' section to let me run it in standalone mode, just to check that there are no errors in that particular file, and it's fine when run in standalone mode.
Based on someone else's advice, I've also tried importing it into another file, just to see whether there was an import error, and once again, it was fine if I added this to the end of settings.py (while using the dev server):
try:
import mlgb.templatetags.mlgb_custom_filters
except Exception, exc:
print 'error importing mlgb_custom_filters'
print exc
Also, INSTALLED_APPS in settings.py includes the line 'mysite.mlgb', and I have also tried putting just 'mlgb' instead of 'mysite.mlgb' there, as yet another person suggested. And I restarted the dev server every time I made a change.
I think I have tried every single suggestion that I have found on the web until now. Does anyone have any new ideas? Could it be anything to do with the fact that I have inherited a directory structure where the template directory is not within the same structure as the application, i.e. it is not under mysite? Scraping the barrel for ideas here! I hope someone can help.
OK, in the situation that I was in when first posting this question, it seems all I actually needed to do was touch a wsgi file under my appname/apache directory to force the application to be refreshed. Yesterday's initial answer was a red herring. Basically I should have touched the file myproject/myapp/apache/myapp.wsgi. Then maybe restart Apache for good measure? But the confusion was caused by the fact that apparently it wasn't enough either simply to restart Apache or to manually recompile the Python. In order to pick up my changes, seems like I needed to touch that wsgi file. Then all is well.
I can now post an answer to my own question thanks to the help of my colleague Masud Khokhar, whose brilliant detective work has saved the day. To recap, my application worked fine until I added a 'load' statement to one of my template files, to load a 'custom filters' module. Masud identified that now I needed to use a full/absolute path to the template file in urls.py instead of a relative one as I had before (and which worked before, until it needed to load the custom filters module). So, in urls.py, I had a section of code as follows:
url(r'^book/(?P<object_id>\d+)/$', 'list_detail.object_detail',
kwargs={
'queryset':Book.objects.all(),
'template_name' : 'mlgb/mlgb_detail.html'
},
name='mlgb_detail'
),
Instead of this:
'template_name' : 'mlgb/mlgb_detail.html'
I needed something like this:
'template_name' : '/THE_FULL_PATH/mlgb/templates/mlgb/mlgb_detail.html'
Made that change - sorted! Thank you once again, Masud.

django internationalization and translations issue

I have a problem with django translations.
Problem 1 - I updated string in django.po file, but the change does not appear on the webpage.
Problem 2 - I have created my own locale file with django-admin.py makemessages -l et, added the translation string into file, but they too do not appear on the page.
I do not think this is setting problem, because the translations from django.po file do appear on the website, its just the changes and the translations from my own generated file that do not appear.
Edit:
My settings.py contains this:
gettext = lambda s: s
LANGUAGE_CODE = 'et'
LANGUAGES = (
('et', gettext('Estonian')),
)
my own locale files are in
/path/to/project/locale/et/LC_MESSAGES/
and the files are
django.mo and django.po
the file I refer to in problem 1 is django own et transaltion, which I changed.
Well, I got this same error a few moments ago. I solved it deleting the "#, fuzzy" tag over the translation strings in my django.po files. It seems that translated text is not served if it got this tag, so make sure to translate the text and then delete this line.
Here is an example of a translated text not server on a po file:
#: course/models.py:13
#, fuzzy
msgid "code"
msgstr "código"
So, just delete the flag and leave it like this:
#: course/models.py:13
msgid "code"
msgstr "código"
I hope this work for you. Good luck!
Reference: http://share-experiences.com/blog/what-fuzzy-means-python-django-gettext/
PD: I know you got this issue a few month ago, but I leave this response due that you we never heard if you got this problem solved.
Had a same/similar issue with translations not showing up. Setting the LOCALE_PATHS fixed the issue:
# settings.py
USE_I18N = True
USE_L10N = True
LOCALE_PATHS = (
'/path/to/djangoapp/locale',
)
Translation files (PO) are loaded in memory only one time, changes to the PO files are not picked up by Django. In order to load the new translation files you need to restart Django (eg. stop/start runserver, Apache or NGINX).
One additional reason for Django translations not working is to compile the .po file with a Python version different than the one being used to run your application. Make sure you use the same version.
Make sure to use ugettext_lazy and not ugettext
If you are using gettext.translation to get the translations, i.e:
text_de = gettext.translation('django', locale_dir, ['de'], fallback=True).ugettext('Welcome to my site')
... and your translation works on the development server but not on production, note that locale_dir must point to your locale directory. It might be located elsewhere on one of the systems. Spent like 2 hrs finding it.
Check for the USE_I18N setting. More info. Anyway, I think by default it's True...