Mon 13 Nov 2017 — Mon 16 Mar 2020

Django

It's a web framework with an ORM, templating and routing build in.

Reverse URL Lookup

from django.core.urlresolvers import reverse

Forms

Django has some form objects for validating and cleaning up data.

These can also help with templating.

ModelForm make a form for a given Django Model, with some customization allowed.

Form Cleaning

  1. Django's own cleaning, which sets up self.cleaned_data.
  2. def clean_field_name(self) methods for each field.
  3. def clean(self) method.

Formsets

Many forms on one page.

Views

get_initial(self)
populates the form fields
get_context_data(self)

Users and Groups

https://docs.djangoproject.com/en/1.11/topics/auth/

"view tools for logging in users, or restricting content"

permissions: yes/no flags designating whether a user may perform a certain task

User object:

  • username
  • password
  • email
  • firstname
  • lastname

Django provides a property request.user. This is also available in templates as {{ user }}.

Their permissions are available as {{ perms }}. https://docs.djangoproject.com/en/1.11/topics/auth/default/#permissions

View tools

Adding @login_required from django.contrib.auth.decorators to a view redirects to the login page if needed.

Alternatively, LoginRequiredMixin does the same thing.

The @user_passes_test decorator also redirects.

@permission_required("app_name.permission_code") .

Django-Admin Permissions

Defaults for each Django model class:

  • add
  • change
  • delete

You can also set permissions per model instance.

Custom permissions go in the model's meta class.

You can access them with user.has_perm('app_name.permission_model').

For example: user.has_perm('chariot.delete_sensor).

Database

DB Transactions

Django runs in autocommit by default (every statement is a transaction).

There is an ATOMIC_REQUESTS setting to have one transaction per web request.

You can also explicitly use the @transaction.atomic decorator.

Models

Models are objects which get serialized from the database.

Model Managers

Each model has at least one manager, which controls how it is fetched from the database.

QuerySets

QuerySets are filtered down .

QuerySets have an as_manager() function, which is helpful.

Signals

Django has a built-in pub-sub event framework called signals.

Django-Pytest

A pytest plugin that knows about your Django settings.

Allows you to run tests using the pytest command instead of manage.py test.

pytest --reuse-db # Use the database from the previous test run
pytest --create-db # Recreate a database from scratch
pytest --reuse-db --create-db # create-db wins

The site cache and mail inbox are cleaned up between each test.

from pytest_django import asserts as django_asserts # django.test.TestCase asserts

@pytest.mark.django_db(transaction=False) # Allow database access
@pytest.mark.urls("myapp.test_urls") # Change `ROOT_URLCONF` setting
def test_stuff(
    # These fixtures are built in
    rf, # `django.test.RequestFactory` object
    client, # `django.test.Client` object
    admin_client,
    admin_user,
    django_user_model, # TODO: what is this?
    django_username_field, # settings.USERNAME_FIELD
    db,
    transactional_db,
    live_server,
    settings, # Django settings module. Automatically reverts at the end of the test.
    django_assert_num_queries # A function which is also a context manager.
):
    print(f"The mock server is available at {live_server.url}.")

Django-Configurations

Django Configurations provides a base class configurations.Configuration.

Classes that inherit from this are settings classes.

Set the DJANGO_CONFIGURATION setting to settings class you want when you run Django DJANGO_CONFIGURATION="LiveConfig" manage.py, (or DJANGO_CONFIG="TestConfig" pytest using django-pytest).