DRY While Working With Choices for Forms

When creating dozens of forms with selection fields for some many-to-one or many-to-many relations, you might find that it's ineffective to create choices for the form fields from querysets formed by the relations defined by ForeignKeys and ManyToManyFields. You have to import the related models, filter the choices analogously to the limit_choices_to parameter, and form a list of tuples again and again.

To get the same choices from the model as in the admin form, you can use the following:
FIELD_CHOICES = SomeModel._meta.get_field("field_name").get_choices()

Then you can modify the text for the null-value choice, like
FIELD_CHOICES[0] = ("" _("- Choose One -"))

or even remove it:

To save the selected object you can simply assign the chosen value to the foreign key, like:
new_instance = SomeModel()
new_instance.field_name_id = form.cleaned_data['field_name']

If you need to do something with the selected object, you can still live without importing specific models and filtering the entries in the same manner as limit_choices_to. To save time, you can use the following function, which returns the queryset containing all the choosable objects:
def get_related_queryset(model, field_name):
Get the queryset for the choices of the field in a model
objects = get_related_queryset(SomeModel, "field_name")
f = model._meta.get_field(field_name)
qs = f.rel.to._default_manager.complex_filter(f.rel.limit_choices_to)
return qs

Just put this function in one of you applications and import it whenever you need to work with forms. And have happy Easter!


Hacking Contributed Models

Django comes with a bunch of contributed applications like auth for authentication, admin for basic data manipulation, or flatpages for the dynamic content that tends to be rarely changed. Sometimes you want to use them, but their functionality doesn't completely fit your needs.

You have several options in that case:
  • Use custom models with one-to-one or many-to-one relations, creating extensions for existing models. The main drawback of this approach is that those custom models will be editable in the contributed administration separately from the origin or you will need to create custom views to combine everything nicely.
  • Use modified duplicates instead of the contributed applications. The main drawback of this case is that it will be hard to manage the updates of the models.
  • Use signals to modify the models. This can be too complicated for simple changes.
  • Modify the properties of the models on the fly.
Let's dig deeper into the last option. When you start the shell or request for a page on the web server, at first Django loads all modules according the order of the INSTALLED_APPS setting. As Python is an interpreted language and all methods and properties are public, you can access and change them on the fly.

For example, if your task is to rename verbose name of groups to "Roles" and show related users at the list view of contributed administration, then it can be achieved by the following code in some model which application appears somewhere below the "django.contrib.auth" in the INSTALLED_APPS.
# -*- coding: UTF-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import Group

def modify_group_class():
""" A function modifying the contributed Group model """
# modifying the verbose names
Group._meta.verbose_name = _("Role")
Group._meta.verbose_name_plural = _("Roles")

def display_users(group):
""" A function displaying users for a group """
links = []
for user in group.user_set.all():
"""<a href="/admin/auth/user/%d">%s</a>""" % (
("%s %s" % ( # show the real name
user.last_name, # or the username
)).strip() or user.username,
return "<br />".join(links)
display_users.allow_tags = True
display_users.short_description = _("Users")

# attaching the new function to the Group model
Group.display_users = display_users

# changing the list_display for the Group model
Group._meta.admin.list_display = ("__str__", "display_users")


As you might see from this example, Group._meta returns the Meta class and Group._meta.admin returns the Admin class for the Group model. You can prove it to yourself by browsing objects in Django shell aka Python IDE.

Use this kind of hacking whenever you reasonably need to change Django core functionalities or some third party modules and have no other choice. However, don't overuse it, 'cause it might lead to difficulties in maintaining the project.


Tips #1

As I can't get to sleep after my last mug of strong black tea, I decided to write my first tips which will make your life easier.

Use consistent and readable coding convention. You know, class names start with capital letters, the variables and functions with small ones. The different words should be connected either using camelCase or by_underscores, but not mixed up in one project. Use triple double quotes """for documentation of functions""" and triple single quotes '''for commenting some code out'''. For readability it is convenient to limit all your lines to 80 symbols. If a statement is very long, put it inside the brackets and then separate into different lines (this is easier to manage than having a backslash (\) before the new line symbol). When debugging and adding print statement or similar, also add some comment like # DEBUG, which can be easily found later. If there is something to improve in the code, add a comment like # TODO with the description of possible improvement. These words are easily findable later. If you have a long list, tuple or dictionary of items, or a function with many arguments which don't fit into the limit of 80 symbols, separate the items with each per line, indented by one tab. Use comma even after the last item unless it is **kwargs. Put the closing bracket after all. This will let you easily rearrange the order or amount of items later.
view = my_special_view(

Access items in administration faster. Instead of browsing through links and loading unnecessary pages before getting to the necessary ones, type in the URI of the required model directly. All lists of objects can be accessed by /admin/<app_name>/<model_name_in_lower_case>/

Use Python IDE and read Django source. Learn and use the interactive development environment, because it is usually a faster (and more attractive) way to learn how the functions work, than writing the code to the files first and checking the results in the browser afterwards. Use the dir() function for all objects to check the available methods and attributes, use the __dict__ attribute for model instances to check its field values, write for-loops for listing out specific attributes from model instances from different querysets. Interaction and visual representation always gives you some better understanding about the architecture than just Django documentation. Also when something is not clear, don't be afraid to read the source. Take advantage of Django being an open source project.
>>> from django.contrib.auth.models import User
>>> for u in User.objects.all():
... u.__dict__
{'username': u'aidas', 'first_name': u'Aidas', 'last_name': u'Bendoraitis', 'is_active': 1, 'email': u'', 'is_superuser': 0, 'is_staff': 0, 'last_login': datetime.datetime(2008, 2, 27, 13, 43, 58), 'password': u'sha1$e55b5$9aa9485f4ad6fc7947e80b63e6d56519c73ac5bb', 'id': 1L, 'date_joined': datetime.datetime(2007, 3, 30, 20, 56, 7)}

That's it for this time. Now it's really time to sleep. :D



Hello Pythoners! Hello Djangoers! Hello other people!

This is yet another blog about Django - the Web framework for perfectionists with deadlines.

I decided to start writing it to log some knowledge that comes from practice of daily work with Django. It's useful to have it for later reference and also for sharing it with you. And you are welcome to comment my code, correct where I am wrong, and open discussions.

If you are not much familiar with Django, but would like to learn it, then I suggest you to read the following resources at first:

Have a nice day.