-
Notifications
You must be signed in to change notification settings - Fork 13
The Basics of Django
First off: read the documentation. The django documentation is amazing, and this is only a very brief overview on the basics of basics. We currently support Django 2.2.13 or later on Python 3.4+.
- When started, django reads the urlpatterns in
lnldb/urls.py
. - This references the 'urls.py' files in each directory (for more concise lists of urls), and builds one massive list from it.
- This list maps regular expressions to a view function, which is just a function in 'views.py' which takes a request and returns a response (there are class-based views too).
- These urls can later be used to generate links using the 'reverse' function or 'url' template function. These are of the form 'appname:viewname'.
- SQL data in django is stored in models and accessed without actually writing any SQL. These live in the models.py in each folder.
- Do queries via the objects member (eg. ModelName.objects.filter(some_field="bar")). You can also traverse across foreign keys (some_fk__remote_field) or apply some criteria (eg. iequals) with a double underscore (dunderscore).
- Models need to be created in the database and updated after you change the layout of its fields using migrations*. These are powerful enough allow you to convert data in any schema over the history of the project to any other schema (usually the most recent one). Generate them with
python manage.py makemigrations
and run withpython manage.py migrate
. - Django crosses foreign key boundaries lazily, so to reduce the total number of SQL queries, use the .select_related and .prefetch_related methods to eager-load foreign-key and many-to-many relations. Django-debug-toolbar is supremely useful here.
It would be a pain to generate HTML in python, so we use the Django Template Language. This was django's original claim-to-fame, and it is generally far easier to edit this part than the python code. Our templates are in the site_tmpl folder, the layout of which is generally a mess, so just check which template file is referenced in the view.
We also make heavy use of object-level permissions (eg. a crew-chief can add a report to their event, but not any event). These are controlled by if-like tags with 'if' replaced by permission (provided by the django-permission package). Eg:
{% permission request.user has 'events.edit_event' of event %}
You can edit {{ event }}!
{% elpermission request.user has 'events.view_event' of event %}
You can view {{ event }}!
{% else %}
Event? What event?
{% endpermission %}