Tag Archives: django

Forgotten password in Django

Turns out that there are plenty of useful features in the Django admin that I never thought about.

The other day I found the last task of a project of mine was adding the "Forgotten password" feature. It's basically a standard task included in every users-related project, but the whole process requires few interactions:

  1. clicking 'forgotten password' link
  2. writing user email where the password should be send to
  3. verifying email against users database
  4. sending confirmation link
  5. confirming link
  6. choosing password
  7. resetting password

The whole 7-steps list (with UI and backend communications) could be boring and time wasting (usually).

That's where Django's templates and integrated behavior comes as a super hero.

Copy all necessary templates from your Django installation

There are few templates that you need to copy from your Django installation. You can find them in your DJANGO_PATH/contrib/admin/templates/registration. You can copy all password-related templates to your templates directory in admin/registration folder.

Some URL paths have to be added to your urls.py file. That's a sample of mine urls.py with the following URLs:


  1. url(r'^registration/(?P<municipality_id>\d+)$', proposal, name='proposal'),
  2. url(r'^login_teacher$', 'django.contrib.auth.views.login', {'template_name': 'view_school_upload.html'}),
  3. url(r'^password_reset$', 'django.contrib.auth.views.password_reset', {'template_name': 'admin/registration/password_reset_form.html', 'email_template_name':'admin/registration/password_reset_email.html'}),
  4. url(r'^password_reset_done$', 'django.contrib.auth.views.password_reset_done', {'template_name': 'admin/registration/password_reset_done.html'}),
  5. url(r'^password_reset_confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)$', 'django.contrib.auth.views.password_reset_confirm', {'template_name': 'admin/registration/password_reset_confirm.html'}),
  6. url(r'^password_reset_complete$', 'django.contrib.auth.views.password_reset_complete', {'template_name': 'admin/registration/password_reset_complete.html'}),


The only one taking parameters is the reset confirm one. Most urls are paramless, but you need to pass the user ID and the hashed value for the confirmation link. 

After you've added all the templates with the right paths and set all urls, you could just navigate your forgotten password link:

  1. <a href="{% url django.contrib.auth.views.password_reset %}">{% trans 'forgot your password' %}</a>

P.S. The whole template pack supports multilingual behavior so after adding the templates, you can run makemessages in order to translate the strings in your language.

Note: in some versions (such as 1.1.1) of Django there is problem with the emailing template. At line 7, remove the named parameters when calling password_reset_confirm view and alter the call only passing values:

  1. {{ protocol }}://{{ domain }}{% url django.contrib.auth.views.password_reset_confirm uid, token %}

del.icio.us Digg DZone Facebook Google Google Reader Magnolia reddit SlashDot Technorati ReadMe.ru Dobavi.com Dao.bg Lubimi.com Ping.bg Pipe.bg Svejo.net Web-bg.com

Django multilingual: select translation instead of ‘None’

If you use the django-multilingual module for multilingual content, you need to add a translation for every language your entity could be seen through. Otherwise you get 'None' as a title (which is way too blurry and quite indescribable). Thanks to my colleague and friend lpetrov I found a way to pass through this limitation and print any possible translation if the current one is not available.

I've added a translation.py file in my project which I import in all my apps when necessary. Here there is the code:

  1. def get_local_str_or_other(obj, field_name):
  2. result = getattr(obj, field_name)
  3. if result:
  4. return result
  5. else:
  6. field_for_search = field_name + "_"
  7. translations = [getattr(obj, field_for_search + lang[0].replace("-","_")) for lang in settings.LANGUAGES]
  8. for translation in translations:
  9. if translation != None:
  10. return unicode(translation)

Later I import the function in my models and I redefine the __unicode__ function. If the name I want to print by default is the field 'title', we have the following:

  1. def __unicode__(self):
  2. return get_local_str_or_other(self, "title")


del.icio.us Digg DZone Facebook Google Google Reader Magnolia reddit SlashDot Technorati ReadMe.ru Dobavi.com Dao.bg Lubimi.com Ping.bg Pipe.bg Svejo.net Web-bg.com

Django debugging (presentation)

 I found a great presentation on Django debugging from Simon Willison.

It's a presentation on "Django 101 in troubleshooting". You could find information how to address any errors from the error pages that django throws away, how to follow stack traces and how to debug information in variety of ways.

Simon pays attention to the basic and the core of all debugging tools - the console. Every single output pass through the console itself so it is the mother of all outputs. Other popular options is the python debugger under the pdb package. 

I personally do like django-debug-toolbar for my apps. It is quite useful for taking care of the HTTP requests and response, passed variables across the website and so on. You could check the number of SQL queries and the load time of your website. Another important feature is printing the list of all templates used for rendering a web page. You could check the settings list for the current page load as well as the signals being called at the moment.

More on the django-debug-toolbar - Rob speaks here.

del.icio.us Digg DZone Facebook Google Google Reader Magnolia reddit SlashDot Technorati ReadMe.ru Dobavi.com Dao.bg Lubimi.com Ping.bg Pipe.bg Svejo.net Web-bg.com

Django translations: multilingual, i18n, app names

 Django is a popular web framework written in Python that provides dynamic generated content and allows rapid development for different systems in the Internet. It provides a great interface to other products (via web services), gives ability to design a scalable application and most important, lies on a powerful language as Python (in other words, what you could do in Python, you could somehow reuse it in Django either by a component or by defining a custom logic down there).

In my experience two of the most important things in a web application (no matter the framework, system and language) are the user management and multilingual support. Django has an Auth module that does most of the things you need - provide users and groups, powerful permission API for each model and action down there and many methods to be overriden from the framework to fine tune the filtering if needed. As for the multilingual support, there are few steps to be followed.

Translating the static content

i18n support for Django - in the Django book. You have the uggettext_lazy (and two more) functions to translate the local based strings in your models, views and so on logic python parts. As for the templates, you could use trans and blocktrans tags for the static content down there.

Translating files is easy - via 'makemessages' and 'compilemessages' you get .po files (for PoEdit or any text editor) and then you compile them for Django to interpret.

Translating models and app names

Translating models for the admin is easy - just add the verbose_name and verbose_name_plural in your Meta class and make that visible for the makemessages.

App names is kind of a mystery for me as well. I saw this guy using the __init__.py and adding application names there. It works for me - my application recognizes them and generates the appropriate literals in the .po files.  


A module named django-localeurl could address all your request to a certain subdirectory for a given language - lets say site.com/en , site.com/es and so on. Based on that your content could automatically detect the current language and load the right translation. Nice, huh?

Multilingual content

django multilingual exampleWhat if you need a content translation for every language in your site? Either it is a news portal or a blog, you could add a new language in the settings.py anytime and just get an additional text field in the admin panel for the new language. This is why django-multilingual exists. You define the fields to be multilingual and you get a field for every language. With the help of localeurl you just get the right translation in the end with some automagic in between :)


At the moment I do use a CountryMiddleware to get the country on request via subdomains. I have Country model which has a name (of the country) and subdomain (for the subdomain). 

A trick to retrieve the subdomain of a webpage you could see here. Then all you need is to call your model and use the get_object_or_404 function to add this one to your request (so the country is visible globally).


del.icio.us Digg DZone Facebook Google Google Reader Magnolia reddit SlashDot Technorati ReadMe.ru Dobavi.com Dao.bg Lubimi.com Ping.bg Pipe.bg Svejo.net Web-bg.com

Django framework – first impressions


I've been researching the Django framework for the last 2-3 weeks in my spare time. It's development is going on and on and I see many interesting innovative concepts realised behind.

I tried it 3 years ago for a course project when we had to integrate the PIL (Python Image Library) into a web project with the existing technology. It was still first version and not much functional though. Poorly documented as well, but as I see now it is almost complete. Python is a powerful language and a web framework based on it i s a great idea.

There are few CMS systems based on Django. Honestly I don't see any sense in any of them - basically because they could save you 4 or 5 hours of work total but with something that could also trick you later. The admin generation is fast enough in Django that you don't need a few days to moderate the administrative panel and do all the necessary relations for the CRUD .

However, there is one thing I do not like in the basic concept. Comparing Django to CakePHP (which has similar abilities in it's latest releases) I feel restricted by the automagic thing. Automagic is a code-behind technique that generates no code in your project but does stuff at the same time. The problem with this all is that you have no idea what happens behind the project itself. In CakePHP you have admin generation in the same way you see it - yes, 'generation' with 'code generation' as well - files + tests are done and added to the project, controllers have their own methods that execute functions and so on. When you change function code, the project acts a different way. In Cake there is automagic as well, for instance if you define function login() {} for the auth module, you already have login system. No fields defined, nor actions. Just an empty login function. But this is more of an exception than to a rule.

When you define a Django project, the admin panel has no fully coded Admin classes. Everything is reused from the parent classes and once you need to change, you need to research either the documentation or the code in order to find the required methods. This is hard to find in the beginning of your Django career having no expectation of the backend and the possibilities of functions for the project.

Anyway, if we agree on a bit harder learning curve, the framework itself give much more than coding from scratch or with any other framework. Powerful applications could be defined if not in hours, in days, and could be deployed in places like the many Django hosting companies abroad. In Bulgaria there are host providers that support Python (via CGI) and install Django framework on request.

del.icio.us Digg DZone Facebook Google Google Reader Magnolia reddit SlashDot Technorati ReadMe.ru Dobavi.com Dao.bg Lubimi.com Ping.bg Pipe.bg Svejo.net Web-bg.com

Python, SVN and Android


Three things with not much in common, except that these are the three interesting things around me these days.

For the last 2 weeks I do python development (actually Django) for an international project while I'm ending my CakePHP and Digital Signer applications. I set up Subclipse in my Eclipse because I got tired of committing twice some of my files. This way my SVN is connected to the project in the IDE and the new data is deployed in an easy and beautiful way without any console commits.

The Django projects are fine as well. I do researches over the multilingual applications. So far I found url-locale and multilingual modules which serve to detect the language via the URL and create a multilingual content while create the intermediate tables for that. I continue researching the session system in order to save the languages there where switching around.

As for the Android, I plan to do my first app for almost a year. Recently I had a few job proposals for Android development plus the Mtel contest for Android app. That's why I downloaded the SDK and the Android plugin and started from the Hello World tutorial online. More researches are done and I am willing to test a more complex application with Internet activity, of course.

del.icio.us Digg DZone Facebook Google Google Reader Magnolia reddit SlashDot Technorati ReadMe.ru Dobavi.com Dao.bg Lubimi.com Ping.bg Pipe.bg Svejo.net Web-bg.com