12 Skill 6 - Using a programming language to develop the software solution
- SAT601: Uses a range of appropriate processing features.
- SAT602: Writes comprehensive internal documentation.
- SAT603: Applies appropriate validation techniques.
- SAT604: Documents evidence of critical and creative thinking through the modification of designs and evaluation criteria.
12.1 SAT601: Uses a range of appropriate processing features.
🚧 Keep building your Django project (MVP) and documenting your code to help you meet this criterion.
12.2 SAT602: Writes comprehensive internal documentation.
12.2.1 Create Internal Documentation with Django
Guides:
12.2.2 Key ideas about comments
12.2.2.1 Create a single-line comment in Python.
# This is a comment12.2.2.2 Create a multiline comment using """.
"""
multiline
comments
"""12.2.2.3 Create multipline comment using #.
# comment line 1
# comment line 212.2.2.4 Create comments in the middle of a line.
Two spaces before the #.
def home(request): # This function will show the home page to visitors12.2.2.5 To add a comment to a function
An indentation (4 spaces) is required.
def test_foo():
"""
A test docstring looks like this (#123456).
"""
12.2.2.6 Avoid using comments that provide no additional information
Do not just explain your code syntax unless it is for learning purposes.
Below is a poor example of just explaning code syntax.
# standard library
import json
from itertools import chain
# third-party
import bcrypt
# Django
from django.http import Http404
from django.http.response import (
Http404,
HttpResponse,
HttpResponseNotAllowed,
StreamingHttpResponse,
cookie,
)
# local Django
from .models import LogEntry
# try/except
try:
import yaml
except ImportError:
yaml = None
CONSTANT = "foo"
class Example: ...12.2.2.7 Use proper naming and parameters
In Django views, the first parameter in a view function should be called request.
def my_view(request, foo): ...For models, field names should be all lowercase, using snake_case instead of camelCase.
class Person(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=40)Jimmy created a model for his super book as below. Fix his mistakes in naming his fields.
class superBook(models.Model):
TitleName = models.CharField(max_length=100)
Author_Name = models.CharField(max_length=50)12.2.2.8 All-uppercase names are typically used for constants and settings
✅Add these comments to your project settings.py
# Language code for Australian English
LANGUAGE_CODE = 'en-au'
# Time zone for Melbourne
TIME_ZONE = 'Australia/Melbourne'12.2.2.9 Use lowercase names for Django apps
Example:
python manage.py startapp polls
12.2.2.10 Places you should comments
- Complex section of code
- TODOs or notes for code not yet written
- Document your code for functions, methods, classes
12.2.3 Real Coding Example
- https://github.com/django/django/blob/main/django/apps/registry.py
class Apps:
"""
A registry that stores the configuration of installed applications.
It also keeps track of models, e.g. to provide reverse relations.
"""
def __init__(self, installed_apps=()):
# installed_apps is set to None when creating the main registry
# because it cannot be populated at that point. Other registries must
# provide a list of installed apps and are populated immediately.
if installed_apps is None and hasattr(sys.modules[__name__], "apps"):
raise RuntimeError("You must supply an installed_apps argument.")
# Mapping of app labels => model names => model classes. Every time a
# model is imported, ModelBase.__new__ calls apps.register_model which
# creates an entry in all_models. All imported models are registered,
# regardless of whether they're defined in an installed application
# and whether the registry has been populated. Since it isn't possible
# to reimport a module safely (it could reexecute initialization code)
# all_models is never overridden or reset.
self.all_models = defaultdict(dict)
# Mapping of labels to AppConfig instances for installed apps.
self.app_configs = {}
# Stack of app_configs. Used to store the current state in
# set_available_apps and set_installed_apps.
self.stored_app_configs = []
# Whether the registry is populated.
self.apps_ready = self.models_ready = self.ready = False
# For the autoreloader.
self.ready_event = threading.Event()
# Lock for thread-safe population.
self._lock = threading.RLock()
self.loading = False
# Maps ("app_label", "modelname") tuples to lists of functions to be
# called when the corresponding model is ready. Used by this class's
# `lazy_model_operation()` and `do_pending_operations()` methods.
self._pending_operations = defaultdict(list)
# Populate apps and models, unless it's the main registry.
if installed_apps is not None:
self.populate(installed_apps)
Jimmy created a module (python file) and add 4 comments (A, B, C, D).
Read each comment and explain how he can improve them.
from django.db import models
# A.
# Define the Student model
# Fields for first name, last name, and birth date
class Student(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
birth_date = models.DateField()# B. add validation later
def full_name(self):
# C. Method to return the full name of the student
return f"{self.first_name} {self.last_name}"
"""D. I would like to discuss improvements on this module with Mr. Chen, or I can come up with new ideas with my partners
"""12.3 SAT603: Applies appropriate validation techniques.
🚧 Django and Python Validation techniques
- Model field validation
- Model
cleanmethod - Form validation
- From
cleanmethod - Decorators:
@login_required,@require_http_methods,@csrf_exemptetc - Signals
- Pydantic to validate and parse data using Python type annotation
- Python: assert
- Python:
tryandexceptblocks
12.3.1 SAT604: Documents evidence of critical and creative thinking through the modification of designs and evaluation criteria.
You can demonstrate this when working on SAT601, SAT602, and SAT603 by extending the examples or completing additional work.