Adam Johnson

Home | Blog | Training | Projects | Colophon | Contact

Posts tagged ‘django’

Introducing time-machine, a new Python library for mocking the current time

Whilst writing Speed Up Your Django Tests, I wanted to add a section about mocking the current time. I knew of two libraries for such mocking, but I found it hard to pick one to recommend due to the trade-offs in each. So I delayed adding that section and shaved a rather large yak by writing a third library.


The Fast Way to Test Django transaction.on_commit() Callbacks

Django’s transaction.on_commit() hook is useful for running tasks that rely on changes in the current database transaction. The database connection enqueues callback functions passed to on_commit, and executes the callbacks after the current transaction commits. If the transaction is rolled back, the callbacks are discarded. This means they act if-and-when the final version of the data is visible to other database connections.


"Speed Up Your Django Tests" is Out Now

My previously announced book “Speed Up Your Django Tests” is out now on Gumroad. I’ve been writing since the 3rd March, so it’s quite a relief to have launched it.


How to Check the Running Django Command

It’s occasionally useful to be able to tell which Django command is being run, in a code path that otherwise has no way of telling. For example, in Speed Up Your Django Tests, I describe how to modify to default use a test settings file when the test command is run.


Book Announcement: Speed Up Your Django Tests

Update (2020-05-18): The book is out now and available for order on Gumroad!


Django Security Headers Hall of Fame

It’s been a year since I published How to Score A+ for Security Headers on Your Django Website, the blog post for my DjangoCon Europe 2019 talk. It’s seen some updates as both Django and web security have evolved, for example Feature-Policy is now required for an A+, and Django 3.0 includes built-in support for Referrer-Policy.


How to Combine Two Python Decorators

Imagine you have some Django views using the same two decorators:


Using Django Check Constraints to Ensure Only One Field Is Set

I previously covered using Django’s CheckConstraint class to validate fields with choices and percentage fields that total 100%. Here’s another use case.


Setting Python's Decimal Context for All Threads

Python’s decimal module has concept of a “context.” This defines the default precision of new Decimals, how rounding works, and lots of other behaviour. Maths gets complicated!


Use Pathlib in Your Django Settings File

Django’s default settings file has always included a BASE_DIR pseudo-setting. I call it a “pseudo-setting” since it’s not read by Django itself. But it’s useful for configuring path-based settings, it is mentioned in the documentation, and some third party packages use it.


All tags: