Models¶
Naming¶
Models should be singular Models are in CammelCase
Must do¶
- Make a
__str__()function because django uses that on many places - Permission should be done through the Meta class
Views¶
Naming¶
Views should be named with snake_case and should end with the word view
Translation¶
Any string in the interface should be translatable
For normal python code that should work as follows:
from django.http import HttpResponse
from django.utils.translation import gettext as _
def my_view(request):
output = _("Welcome to my site.")
return HttpResponse(output)
<title>{% translate "This is the title." %}</title>
<title>{% translate myvar %}</title>
Testing¶
We all know that writing tests is a boring process but it helps with keeping the project stable.
For what should you write test: User input is used: What is the user enters a negative value, what is the input is empty The code handles some kind of validation of authorization: can user x do y
Example test
from django.test import TestCase
from myapp.models import Animal
# Create a test class this bundles tests
# This is handy when you want to run the test for a specific part of the code
class AnimalTestCase(TestCase):
def setUp(self):
Animal.objects.create(name="lion", sound="roar")
Animal.objects.create(name="cat", sound="meow")
# Make a test function make sure the name starts with "test" otherwise it will be run by the test runner
def test_animals_can_speak(self):
"""Animals that can speak are correctly identified"""
lion = Animal.objects.get(name="lion")
cat = Animal.objects.get(name="cat")
self.assertEqual(lion.speak(), 'The lion says "roar"')
self.assertEqual(cat.speak(), 'The cat says "meow"')
Logging (no print statements)¶
During development you can use all the print statements you like. But before mergeing with dev or master these should be removed. If you still want to print handy info the console please use a logger with the correct log level.
# import the logging library
import logging
# Get an instance of a logger
logger = logging.getLogger(__name__)
# Log some handy info to the logger with a warning level
logger.warning('There was a warning loged at '+str(datetime.datetime.now())+' please fix it!')