Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming convention for Django URL, templates, models and views

I know there are a lot of naming conventions to build apps (name database tables in the singular, models in uppercase, and packages all lowercase), but I haven't found any recommendations to name related elements. Something like "If you name your url x, then your view should be named xview" would be useful.

I have decided to use the following rules with writing my first Django App, but I feel that I might be breaking some DRYesque principle. Is there anything wrong with how I am naming URL, templates, models and views?

Create

  1. URL: car/put
  2. view: car_put(); view name: car_put
  3. model: Car
  4. template: car_put.html

Read

  1. URL: car/1 (gets car with id 1);
  2. view: car_get(); view name: car_get
  3. model: Car
  4. template: car_get.html

Update

  1. URL: car/patch/1 (edits car with id 1)
  2. view: car_patch(); view name: car_patch
  3. model: Car
  4. template: car_patch.html

Delete

  1. URL: car/delete/1 (deletes car with id 1)
  2. view: car_delete(); view name: car_delete
  3. model: Car
  4. template: car_delete.html

I am not building an API, the naming rules that can be inferred from the above example are inspired by REST, but my purpose is not to build an API, just to better organize my code.

like image 422
Federico Avatar asked Aug 04 '15 18:08

Federico


1 Answers

At first sight there's no standard, but the usual naming convention is perfectly specified in the wonderful Django Rest Framework, which is almost identical to the style found on the Django tutorial but a little more obvious. If you wanna follow a style, follow that one.

For a Car model the URLs would be (styled as action url):

  • list /cars/
  • create /cars/new/
  • detail /cars/1/
  • update /cars/1/edit/
  • delete /cars/1/delete/
  • any methods not dependent on an object /cars/view-name/
  • any methods dependent on a particular object /cars/1/view-name/

Something you forgot are the URL names (unless this is what you mean with 'view name'), which would be model-action. e.g. car-list.

The same model_name plus action is used for the Template names (in snake_case) and the View names (in CapitalCase).

Wait, why CapitalCase? Because a much more important standard than naming conventions is to use the powerful class-based views, as opposed to the old method-based views, which lack inheritance and ease of structuring.

If you read the tutorial you'll notice it begs you to upgrade from method-based to class-based views at around the half-point. Method-based views are useful only for very tiny operations and well, introducing you to Views in the Django Tutorial :P

TL;DR: Do as you wish (though I applaud your OCD :P) but if there's something to take away fromm this post is: use class-based views.

like image 161
Agustín Lado Avatar answered Sep 18 '22 15:09

Agustín Lado