Services Blog Français

Coding standards for Django apps: names

| by jpic | django best-practice

This post shows a coding standard which emerged from the Pinax community (formerly hot-club)[source needed] for predictive and consistent URL naming patterns. While this is still supported by Django, namespaced URL include() has been as well for some years now and urls should be translated when upgrading Django versions. Django Contributing Commons maintains a technical description which you can reuse in your project. Check it out and try to contribute, this could be a nice community driven git based coding standards for Django !

Here goes, for history:

Naming stuff in Django apps consists of using:

  • the application name
  • a model name
  • an action name

Naming views

View names are composed of 2 items which are separated by an underscore:

  • the model name
  • the action name

Common cases are:

  • post_detail
  • band_create
  • user_list
  • group_delete

Naming urls, legacy

My standard is older that namespaced urls. It is composed of the following elements separated by an underscore:

  • app name
  • view name as above

For example:

  • blog_post_detail
  • band_band_create
  • auth_user_list
  • auth_group_delete

band_band_create ? Well if the url is for creating a Band model instance from the band app, so that’s pretty self-documenting.

Prefixing url names with the application name was a very nice way of avoiding conflicts between url names.

Naming urls with namespaces

Since Django 1.1, this is not necessary anymore because of namespaced urls inclusion. Instead of including your blog app urls as such:

    url(r'blog/', include('blog.urls')),

And reversing as such:

    {% url 'blog_post_detail' post.pk %}

You could include your blog app urls with the blog app namespace:

    url(r'blog/', include('blog.urls', app_name='blog'))

Thus, if you named the post_detail view url just post_detail, there should be no conflict reversing as such:

    {% url 'blog:post_detail' post.pk %}

Both are good as long at it is consistent per app.

Naming templates

Templates should live in an application-specific directory be named after their views. For example:

  • blog/post_detail.html
  • band/band_create.html
  • auth/user_list.html
  • auth/group_delete.html

Further reading

They trust us

Contact

logo