Simon Willison’s Weblog

Subscribe

Posts tagged django in Apr

Filters: Month: Apr × django × Sorted by date

Django: what’s new in 5.2. Adam Johnson provides extremely detailed unofficial annotated release notes for the latest Django.

I found his explanation and example of Form BoundField customization particularly useful - here's the new pattern for customizing the class= attribute on the label associated with a CharField:

from django import forms

class WideLabelBoundField(forms.BoundField):
    def label_tag(self, contents=None, attrs=None, label_suffix=None):
        if attrs is None:
            attrs = {}
        attrs["class"] = "wide"
        return super().label_tag(contents, attrs, label_suffix)

class NebulaForm(forms.Form):
    name = forms.CharField(
        max_length=100,
        label="Nebula Name",
        bound_field_class=WideLabelBoundField,
    )

I'd also missed the new HttpResponse.get_preferred_type() method for implementing HTTP content negotiation:

content_type = request.get_preferred_type(
    ["text/html", "application/json"]
)

# 10th April 2025, 4:27 pm / django, python, adam-johnson

Composite primary keys in Django. Django 5.2 is out today and a big new feature is composite primary keys, which can now be defined like this:

class Release(models.Model):
    pk = models.CompositePrimaryKey(
        "version", "name"
    )
    version = models.IntegerField()
    name = models.CharField(max_length=20)

They don't yet work with the Django admin or as targets for foreign keys.

Other smaller new features include:

  • All ORM models are now automatically imported into ./manage.py shell - a feature borrowed from ./manage.py shell_plus in django-extensions
  • Feeds from the Django syndication framework can now specify XSLT stylesheets
  • response.text now returns the string representation of the body - I'm so happy about this, now I don't have to litter my Django tests with response.content.decode("utf-8") any more
  • a new simple_block_tag helper making it much easier to create a custom Django template tag that further processes its own inner rendered content
  • A bunch more in the full release notes

5.2 is also an LTS release, so it will receive security and data loss bug fixes up to April 2028.

# 2nd April 2025, 2:51 pm / django, python

Enforcing conventions in Django projects with introspection (via) Luke Plant shows how to use the Django system checks framework to introspect models on startup and warn if a DateTime or Date model field has been added that doesn’t conform to a specific naming convention.

Luke also proposes “*_at” as a convention for DateTimes, contrasting with “*_on” or “*_date” (I prefer the latter) for Dates.

# 3rd April 2024, 2:58 pm / django, luke-plant

Django 4.2 released. “This version has been designated as a long-term support (LTS) release, which means that security and data loss fixes will be applied for at least the next three years.” Some neat new async features, including improvements to async streaming responses.

# 3rd April 2023, 2:14 pm / async, django

Weeknotes: Vaccinate The States, and how I learned that returning dozens of MB of JSON works just fine these days

Visit Weeknotes: Vaccinate The States, and how I learned that returning dozens of MB of JSON works just fine these days

On Friday VaccinateCA grew in scope, a lot: we launched a new website called Vaccinate The States. Patrick McKenzie wrote more about the project here—the short version is that we’re building the most comprehensive possible dataset of vaccine availability in the USA, using a combination of data collation, online research and continuing to make a huge number of phone calls.

[... 1,109 words]

Porting VaccinateCA to Django

Visit Porting VaccinateCA to Django

As I mentioned back in February, I’ve been working with the VaccinateCA project to try to bring the pandemic to an end a little earlier by helping gather as accurate a model as possible of where the Covid vaccine is available in California and how people can get it.

[... 2,157 words]

Django Release Cycle (via) Really nice visual representation of Django’s release cycle, built by Jeff Triplett as a remix of the Python release cycle by Dustin Ingram.

# 3rd April 2020, 4:56 pm / django, jeff-triplett

How to Create an Index in Django Without Downtime (via) Excellent advanced tutorial on Django migrations, which uses a desire to create indexes in PostgreSQL without locking the table (with CREATE INDEX CONCURRENTLY) to explain the SeparateDatabaseAndState and atomic features of Django’s migration framework.

# 11th April 2019, 3:06 pm / django, migrations, postgresql, zero-downtime

The problem with laziness: minimising performance issues caused by Django’s implicit database queries (via) The ability to accidentally execute further database queries by traversing objects from a Django template is a common source of unexpected performance regressions. django-zen-queries is a neat new library which provides a context manager for disabling database queries during a render (or elsewhere), forcing queries to be explicitly executed in view functions.

# 3rd April 2019, 3:49 pm / django

Feature Flags, from PyCon 2014. Slides from a 15 minute talk I gave at PyCon 2014 about feature flags - what they are, how to use them and how we implemented them at both Lanyrd and Eventbrite.

This was part of a longer workshop on Advanced Django Patterns from Eventbrite and Lanyrd, which I co-presented with Andrew Godwin and Nathan Yergler.

# 10th April 2014, 6:27 pm / django, pycon, python, speaking, my-talks, feature-flags

Introduction to Surlex. A neat drop-in alternative for Django’s regular expression based URL parsing, providing simpler syntax for common path patterns.

# 11th April 2010, 7:23 pm / codysoyland, django, python, regex, surlex, urls

django-piston. Promising looking Django mini-framework for creating RESTful APIs, from the bitbucket team. Ticks all of Jacob’s boxes, even including built-in pluggable authentication support with HTTP Basic, Digest and OAuth out of the box.

# 30th April 2009, 7:55 pm / apis, authentication, bitbucket, digest, django, jespernoehr, oauth, piston, python, rest, restful

REST worst practices. Jacob Kaplan-Moss’ thoughts on the characteristics of a well designed Django REST API library, from November 2008.

# 30th April 2009, 7:53 pm / django, jacob-kaplan-moss, python, rest

python-sqlparse (via) Python library for re-identing SQL statements. This could make debugging Django’s generated SQL a whole lot easier. You can try the library out using an App Engine hosted application (complete with an API).

# 28th April 2009, 8:25 pm / appengine, django, python, sql, sqlparse

Haystack (via) A brand new modular search plugin for Django, by Daniel Lindsley. The interface is modelled after the Django ORM (complete with declarative classes for defining your search schema) and it ships with backends for both Solr and pure-python Whoosh, with more on the way. Excellent documentation.

# 17th April 2009, 9:53 pm / daniel-lindsley, django, haystack, orm, python, search, solr, whoosh

Reducing XSS by way of Automatic Context-Aware Escaping in Template Systems (via) The Google Online Security Blog reminds us that simply HTML-escaping everything isn’t enough—the type of escaping needed depends on the current markup context, for example variables inside JavaScript blocks should be escaped differently. Google’s open source Ctemplate library uses an HTML parser to keep track of the current context and apply the correct escaping function automatically.

# 14th April 2009, 9:26 am / ctemplate, django, escaping, google, html, open-source, security, xss

django-shorturls. Jacob took my self-admittedly shonky shorter URL code and turned it in to a proper reusable Django application.

# 13th April 2009, 9:31 am / django, djangoshorturls, jacob-kaplan-moss, python, revcanonical

rev=canonical bookmarklet and designing shorter URLs

I’ve watched the proliferation of URL shortening services over the past year with a certain amount of dismay. I care about the health of the web and try to ensure that URLs I am responsible will last for as long as possible, and I think it’s very unlikely that all of these new services will still be around in twenty years time. Last month I suggested that the Internet Archive start mirroring redirect databases, and last week I was pleased to hear that Archiveteam, a different organisation, had already started crawling.

[... 920 words]

Scaling Django web apps on Apache. Cool to see this kind of article cropping up on IBM developerWorks, but it’s a shame they don’t mention mod_wsgi.

# 10th April 2009, 9:23 am / apache, django, ibm, modwsgi, python

How to use Django with Apache and mod_wsgi. My favourite deployment option is now included in the official Django docs, thanks to Alex Gaynor. I tend to run a stripped down Apache with mod_wsgi behind an nginx proxy, and have nginx serve static files directly. This avoids the need for a completely separate media server (although a separate media domain is still a good idea for better client-side performance).

# 1st April 2009, 12:24 am / alex-gaynor, deployment, django, modwsgi, nginx, proxy, python, wsgi

QuerysetRefactorBranch. What’s new and changed now that queryset-refactor has merged to trunk.

# 27th April 2008, 7:34 am / django, python, querysetrefactor

Multiple inheritance of newforms and modelforms. If you ever see “Error when calling the metaclass bases metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases” when trying multiple inheritance with newforms and modelforms, here’s a scary solution I found.

# 12th April 2008, 12:54 pm / django, inheritance, metaclasses, modelforms, multipleinheritance, newforms, python

Sharedance (via) “Sharedance is a high-performance server that centralize ephemeral key/data pairs on remote hosts, without the overhead and the complexity of an SQL database.”—ideally suited to session data, which is a poor fit for a full relational database.

# 12th April 2008, 10:39 am / django, sessions, sharedance

Active on IRC in the past hour. New Django People feature in collaboration with Brian Rosner—DjangoBot now provides information on currently active IRC participants. There’s an opt-out privacy control and the bot sends you a message about it the first time it logs your activity.

# 12th April 2008, 12:58 am / django, django-people, irc, python

django-rosetta—Google Code. Very classy Django-powered interface for both reading and writing your project’s gettext catalog files, hence allowing application translators to work through a web interface.

# 11th April 2008, 7:31 am / django, djangorosetta, gettext, i18n, internationalisation

Google App Engine for developers. Best in-depth coverage so far, from Niall Kennedy. I didn’t know that Guido had worked on the Django compatibility layer.

# 10th April 2008, 11:14 pm / django, googleappengine, guido-van-rossum, niall-kennedy, python

The Google App Engine model class, db.Model, is not the same as the model class used by Django. As a result, you cannot directly use the Django forms framework with Google App Engine. However, Google App Engine includes a module, db.djangoforms, which casts between the datastore models used with Google App Engine and the Django models specification. In most cases, you can use db.djangoforms.ModelForm in the same manner as the Django framework.

Google App Engine docs

# 8th April 2008, 1:48 pm / django, google, googleappengine, modelforms, newforms, python

Running Django on Google App Engine. Django 0.96 is included, but you need to disable the ORM related parts and use the Google App Engine Bigtable interface instead.

# 8th April 2008, 1:15 pm / django, google, googleappengine, python

Why the webstandards world appears to be choosing Django. I’m not convinced that this is a definite trend, but it certainly makes for an interesting discussion.

# 4th April 2008, 8:33 am / django, gareth-rushgrove, python, web-standards