Category: Django

Django `CheckboxSelectMultiple` with `ModelMultipleChoiceField` generates too many queries (solution)

If you use  django.forms.ModelMultipleChoiceField with the default widget ( django.forms.widgets.SelectMultiple ), all’s good.

However, if you need to generate checkboxes for your choices, and use  django.forms.widgets.CheckboxSelectMultiple you’ll notice that the field will generate alot of queries (one for each element in the queryset), which is really really bad. I personally ended up with hundred of queries.

Fix: add  cache_choices=True to your  django.forms.ModelMultipleChoiceField

Example:

Good practice:

Bad practice:

django-logo-negative

Django get current user globally in the project

Sometimes, you will need to get the current authenticated user in models, or other parts of your app.

To achieve this, you must create this middleware and add it to MIDDLEWARE_CLASSES in project settings:

Usage example:

Invalidate template fragment cache in Django 1.5

Django 1.5 does not have a utility method to delete template fragment cache, with arguments.

In order to achieve this, you must create a custom method:

Example usage:

… and delete the cache:

 

In django 1.6+ you can do this more easy:

Manually generate Django password reset token

Ever needed to manually generate a password reset token?

For example, imagine this situation:
You create a user from a custom form, and you want the user to set his own password.
Solution: generate a password reset token,  email him the link, and let him choose his own password.

Here’s how you implement this:

To display the link in the email, you must set the password reset url, and display it:

 

Compare integer variable in django templates

Ever needed to compare some variable (that may come from db, forms, etc) in django templates with an integer?
Example:

The above example will not work. Django’s template engine interprets the variable as a string.

Workaround for integer comparison:

By using the “add” filter, the variable is transformed into an integer.