Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Caktus CTO Colin Copeland Invited to the White House Open Police Data Initiative
We at Caktus were incredibly proud when the White House Police Data Initiative invited CTO Colin Copeland to celebrate their first year accomplishments. While at the White House, Colin also joined private breakout sessions to share ideas with law enforcement officials, city staff, and other civic technologists from across the country. Colin is the co-founder of Code for Durham and served as lead developer for OpenDataPolicingNC.com. OpenDataPolicingNC.com, a site built for the Southern Coalition for Social Justice, displays North Carolina police stop data. -
Why using factories in Django
From the very beginning of a project, you need some data. You need data in your development database and you need data for your automated tests. The instinctive solution is to manually enter a set of data via the Django admin. The official way is to enter data via Django fixtures file(s). Using factories will make it easier and better; here is why. -
What We’re Clicking - April Link Roundup
It’s time for this month’s roundup of articles and posts shared by Cakti that drew the most attention on Twitter. The list highlights new work in civic tech and international development as well as reasons for the increasing popularity of Python and open source development. -
How to track Google Analytics pageviews on non-web requests (with Python)
tl;dr; Use raven's ThreadedRequestsHTTPTransport transport class to send Google Analytics pageview trackings asynchronously to Google Analytics to collect pageviews that aren't actually browser pages. We have an API on our Django site that was not designed from the ground up. We had a bunch of internal endpoints that were used by the website. So we simply exposed those as API endpoints that anybody can query. All we did was wrap certain parts carefully as to not expose private stuff and we wrote a simple web page where you can see a list of all the endpoints and what parameters are needed. Later we added auth-by-token. Now the problem we have is that we don't know which endpoints people use and, as equally important, which ones people don't use. If we had more stats we'd be able to confidently deprecate some (for easier maintanenace) and optimize some (to avoid resource overuse). Our first attempt was to use statsd to collect metrics and display those with graphite. But it just didn't work out. There are just too many different "keys". Basically, each endpoint (aka URL, aka URI) is a key. And if you include the query string parameters, the number of keys … -
Florida Open Debate Platform Receives National Attention (The Atlantic, USA Today, Engadget)
Several national publications have featured the Florida Open Debate platform, including USA Today, Engadget, and The Atlantic. Caktus helped develop the Django-based platform on behalf of the Open Debate Coalition (ODC) in advance of the nation’s first-ever open Senate debate held in Florida on April 25th. The site enabled citizens to submit debate questions as well as vote on which questions mattered most to them. Moderators then used the thirty most popular questions from the site to structure the debate between Florida Senate candidates David Jolly (R) and Alan Grayson (D). According to *The Atlantic, *more than 400,000 votes were submitted by users on the site, including more than 84,000 from Florida voters. -
ES6 For Django Lovers
ES6 for Django Lovers! The Django community is not one to fall to bitrot. Django supports every new release of Python at an impressive pace. Active Django websites are commonly updated to new releases quickly and we take pride in providing stable, predictable upgrade paths. -
Multi-table Inheritance and the Django Admin
Django's admin interface is a great way to be able to interact with your models without having to write any view code, and, within limits, it's useful in production too. However, it can quickly get very crowded when you register lots of models. Consider the situation where you are using Django's multi-table inheritance: {% highlight python %} from django.db import models from model_utils.managers import InheritanceManager class Sheep(models.Model): sheep_id = models.AutoField(primary_key=True) tag_id = models.CharField(max_length=32) date_of_birth = models.DateField() sire = models.ForeignKey('sheep.Ram', blank=True, null=True, related_name='progeny') dam = models.ForeignKey('sheep.Ewe', blank=True, null=True, related_name='progeny') objects = InheritanceManager() class Meta: verbose_name_plural = 'sheep' def __str__(self): return '{}: {}'.format(self._meta.verbose_name, self.tag_id) class Ram(Sheep): sheep = models.OneToOneField(parent_link=True) class Meta: verbose_name = 'ram' verbose_name_plural = 'rams' class Ewe(Sheep): sheep = models.OneToOneField(parent_link=True) class Meta: verbose_name = 'ewe' verbose_name_plural = 'ewes' {% endhighlight %} Ignore the fact there is no specialisation on those child models: in practice you'd normally have some. Also note that I've manually included the primary key, and the parent link fields. This has been done so that the actual columns in the database match, and in this case will all be `sheep_id`. This will make writing joins slightly simpler, and avoids the (not specific to Django) ORM anti-pattern of … -
(Directly) Testing Django Formsets
Django Forms are excellent: they offer a really nice API for validating user input. You can quite easily pass a dict of data instead of a `QueryDict`, which is what the request handling mechanism provides. This makes it trivial to write tests that exercise a given Form's validation directly. For instance: {% highlight python %} def test_my_form(self): form = MyForm({ 'foo': 'bar', 'baz': 'qux' }) self.assertFalse(form.is_valid()) self.assertTrue('foo' in form.errors) {% endhighlight %} Formsets are also really nice: they expose a neat way to update a group of homogenous objects. It's possible to pass a list of dicts to the formset for the `initial` argument, but, alas, you may not do the same for passing data. Instead, it needs to be structured as the `QueryDict` would be: {% highlight python %} def test_my_formset(self): formset = MyFormSet({ 'formset-INITIAL_FORMS': '0', 'formset-TOTAL_FORMS': '2', 'formset-0-foo': 'bar1', 'formset-0-baz': 'qux1', 'formset-1-foo': 'spam', 'formset-1-baz': 'eggs' }) self.assertTrue(formset.is_valid()) {% endhighlight %} This is fine if you only have a couple of forms in your formset, but it's a bit tiresome to have to put all of the prefixes, and is far noisier. Here's a nice little helper, that takes a `FormSet` class, and a list (of dicts), and instantiates … -
2016 DBIR Highlights
The 2016 edition of Verizon’s Data Breach Investigations Report is out, and as usual it’s compelling reading. The DBIR is one of the only sources of hard data about information security, which makes it a must-read for anyone trying to run a security program in a data-driven manner. What follows are the bits that I found especially interesting, and a bit of my own commentary. Internal threats are rare [T]he Actors in breaches are predominantly external. -
Florida Open Debate Site Powers First-Ever Crowd-Sourced Open Senate Debate
Florida Open Debate launched ahead of the upcoming, bi-partisan debate between candidates for the Florida Senate. The site, which crowdsources debate questions from the general public, was met with national acclaim. Citizens can not only submit questions, but also vote on which ones matter most. Caktus helped develop the tool on behalf of the Open Debate Coalition (ODC), a non-partisan organization dedicated to supporting participatory democracy through the use of civic tech. -
Django: Running management commands inside a Docker container
Okay, so we have dockerized our django app and we need to run a manage.py command for some task. How do we do that? Simple, we have to locate the container that runs the django app, login and then run the command. Locate The Container It’s very likely that our app uses multiple containers to compose the entire system. For exmaple, I have one container running MySQL, one container running Redis and another running the actual Django app. If we want to run manage.py commands, we have to login to the one that runs Django. While our app is running, we can find the running docker containers using the docker ps command like this: $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 308f40bba888 crawler_testscript "/sbin/my_init" 31 hours ago Up 3 seconds 5000/tcp crawler_testscript_1 3a5ccc872215 crawler_web "bash run_web.sh" 31 hours ago Up 4 seconds 0.0.0.0:8000->8000/tcp crawler_web_1 14f0e260fb2c redis:latest "/entrypoint.sh redis" 31 hours ago Up 4 seconds 0.0.0.0:6379->6379/tcp crawler_redis_1 252a7092870d mysql:latest "/entrypoint.sh mysql" 31 hours ago Up 4 seconds 0.0.0.0:3306->3306/tcp crawler_mysql_1 In my case, I am using Docker Compose and I know my Django app runs using the crawler_web image. So we note the name of the container. In … -
How to create Custom User Model in Django?
Django provides built-in authentication which is good for most of the cases, but you may have needs that are being served by the existing system. For Ex: You want 'email' for authentication purpose rather than Django's username field and you want an extra field called 'display_name' as a full name for the logged in User. To meet the above requirements, we need to customize Django's built-in user model or substitute a completely customized model. In this blog post, we'll learn how to customize Django's built-in User model. Its good idea to extend Django User Model rather than writing whole new user model and there are a lot of ways but one good way is to extend it from Django itself. We get all features and properties of Django User and our own custom features on top of it. Add the following to your app that holds custom user model. In models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): name = models.CharField(max_length=100, blank=True, null=True) and specify your custom user model in settings.py AUTH_USER_MODEL = ‘your_app.User' If you want to use your custom user model in models.py, you can get that model with `settings.AUTH_USER_MODEL` or `get_user_model()` of Django's … -
Autocomplete Search in Django with Haystack & Elasticsearch
How to build autocomplete (type-ahead) search in Django with django-haystack and Elasticsearch: the EdgeNgram analyzer, EdgeNgramField, SearchQuerySet().autocomplete(), single-letter min_gram tuning, a JSON endpoint with a debounced JS search box — plus honest 2026 alternatives (elasticsearch-dsl completion suggester, PostgreSQL trigram, Meilisearch/Typesense) and Elasticsearch/OpenSearch version pinning. -
A reading list for InfoSec engineers
I’ve started a curated reading list for InfoSec engineers. I was inspired by Mark McGranaghan’s Services Engineering reading list. I really enjoy these kinds of personal, highly-curated reading lists, and for some time I’ve wanted to pull together one of my own. This is my list, not a definitive one — that is, these are resources I’ve found useful. As such it has some biases: It’s oriented towards providers of Software-, Platform-, and Infrastructure-as-a-Service. -
Django REST Framework: Remember to disable Web Browsable API in Production
So this is what happened – I built an url shortening service at work for internal use. It’s a very basic app – shortens urls and tracks clicks. Two models – URL and URLVisit. URL model contains the full url, slug for the short url, created time etc. URLVisit has information related to the click, like user IP, browser data, click time etc and a ForeignKey to URL as expected. Two different apps were using this service, one from me, another from a different team. So I kept the Web Browsable API so the developers from other teams can try it out easily and they were very happy about it. The only job of this app was url shortening so I didn’t bother building a different home page. When people requested the / page on the domain, I would redirect them directly to /api/. Things were going really great initially. There was not very heavy load on the service. Roughly 50-100 requests per second. I would call that minimal load. The server also had decent hardware and was running on an EC2 instance from AWS. nginx was on the front while the app was run with uwsgi. Everything was so … -
Psychological safety in the InfoSec industry
My co-worker Eric Mill recently brought up the topic of psychological safety. Referencing a study by Google that points to psychological safety as a key factor in successful teams, Eric wrote: Maybe these situations sounds familiar to others (they definitely both are to me): Did you feel like you could ask what the goal was without the risk of sounding like you’re the only one out of the loop? -
factory_boy in Django: A Better Alternative to Fixtures
Static Django fixtures rot on every schema change. Learn how to use factory_boy instead: declarative factories with Faker, Sequence, SubFactory and post_generation for relations, build() vs create(), traits, batches, and integration with pytest-django and TestCase. -
Generic Many-to-Many Relationships in Django
Django's built-in ManyToManyField can only point at one model. Learn how to build a generic many-to-many relation in Django 5.x with the contenttypes framework — a GenericForeignKey through model plus GenericRelation accessors — using a clean, reusable tagging example. -
Monitor Celery Task Queues with Flower
Flower is a real-time, web-based dashboard for monitoring and administering Celery workers and tasks. This 2026 guide shows how to install Flower, run it on port 5555 with Celery 5.x, watch workers, tasks, arguments and graphs, secure it for production with basic auth or OAuth behind Nginx and TLS, and pair it with Prometheus and Grafana. -
How to Create Initial Django Migrations for an Existing Database
Two scenarios, two fixes: adopt migrations for an existing Django schema with makemigrations and migrate --fake-initial, or bring a legacy database under Django with inspectdb - plus how to safely reset or squash a messy migration history. -
Check test coverage in Django code with Coveralls
Coverage: It is a tool used for showing the percentage of your codebase covered by tests. Test Coverage is an important indicator of software quality and an essential part of software maintenance. It helps in evaluating the test cases by providing the data on different coverage items. It is a useful tool for finding untested part of a code. Test coverage can help in monitoring the quality of testing and assist in directing the test generators to create test cases that cover areas that have not been tested. It helps to measure the quality and identifies unnecessary test cases which will not increase coverage. Benefits of Test Coverage: Defect prevention in the project. It creates additional test cases to increase coverage. It helps in determining a quantitative measure of code coverage, which indirectly measures the quality of the application or product. Installation: Pip install coverage Use "coverage run" to run your program and gather data: coverage run manage.py test coverage report -m # provides the report for the tests Individual app test can be run using the command coverage run --source=app1,app2 manage.py test -
From Intern to Professional Developer: Advice on a Mid-Career Pivot
A few weeks ago, Rebecca Conley attended DjangoCon Europe 2016 in Budapest, Hungary. The event is a five-day conference that brings together Django lovers from all over the world to learn about and share each other’s experiences with Django. -
Adopting Scrum in a Client-services, Multi-project Organization
Caktus began the process of adopting Scrum mid-November 2015 with two days of onsite Scrum training and fully transitioned to a Scrum environment in January 2016. From our original epiphany of “Yes! We want Scrum!” to the beginning of our first sprint, it took us six weeks to design and execute a process and transition plan. This is how we did it: -
Django Forms basics explained
Django forms is powerful module to help Django application development in rendering html from model, validate input from httprequest to model specifications. And we can extend the module to suit our exact need. Lets see basics of django forms. Forms: A collection of fields that knows how to validate itself,Form classes are created as subclasses of django.forms.Form Example: Consider a form used to implement add menu item functionality create models.py from django.db import models class Menu(models.Model): title = models.CharField(max_length=100) content = models.CharField(max_length=100) order = models.IntegerField() create forms.py from django import forms class MenuForm(forms.Form): title = forms.CharField(max_length=100) content = forms.CharField(max_length=100) order = models.IntegerField() A form is composed of Field objects. Using a form in a view: django.http import HttpResponse from app.forms import MenuForm def add_menu(request): if request.method == "POST": form = MenuForm(request.POST) if form.is_valid(): title = request.POST.get("title") content = request.POST.get("content") order = Menu.objects.all().count() + 1 menu = Menu.objects.create(title=title,content=content, order=order) return HttpResponse("Menu Successfully created") … -
How to Add CAPTCHA to Django Forms
A current, Django 5.x guide to adding CAPTCHA and bot protection to your forms. Install django-recaptcha for reCAPTCHA v2 and v3, compare Cloudflare Turnstile and hCaptcha, and validate every response server-side.