Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Onnx Machine Learning in Production
I recently had a project that ... -
Django Signup Tutorial
Previously we [added login and logout pages](https://learndjango.com/tutorials/django-login-and-logout-tutorial) to our Django app. In this tutorial we'll create a sign up page so users can register for a new account. The [Django … -
Django News - PyConline AU Talks Now Live! - Sep 11th 2020
News Django Technical Board Candidate Registration Registration for Candidates will end on September 11th, 2020 AoE. djangoproject.com Django-Developers Discussion: Generate JWTs with Django django-developers is the official Google Group for discussion of Django technical features and recently questions around JWTs were discussed. google.com Events DjangoCon Europe Schedule is out! September 18 & 19 Note that the timezone is GMT+1 djangocon.eu DjangoCon Europe 2020 Tickets DjangoCon Europe 2020 is one week away! pretix.eu PyGotham TV's schedule is out! October 2 & 3 PyGotham TV's schedule is out and is free to attend. pygotham.tv Articles Django Hosting & Deployment Options Will Vincent does a rundown on popular Platform-as-a-service (PaaS) and virtual private server (VPS) hosting/deployment options for Django. learndjango.com From Concept To Live In Two Weeks With Django Matt Layman's very good rundown of building a Django + Tailwind CSS + Heroku project for a non-profit in only 2 weeks. mattlayman.com What happens when you run manage.py test? Adam Johnson's PyConAU talk which details Django testing internals. Complements his PyConAU talk in the Videos section. adamj.eu Demystifying Django’s Magic Precious Ndubueze's overview of what Django brings to the table as a web framework. smashingmagazine.com Videos PyConline AU 2020 The full PyConline AU … -
Not all attacks are equal: understanding and preventing DoS in web applications
Denial-of-Service (DoS) vulnerabilities are common, but teams frequently disagree on how to treat them. The risk can be difficult to analyze: I’ve seen development teams argue for weeks over how to handle a DoS vector. This article tries to cut through those arguments. It provides a framework for engineering and application security teams to think about denial-of-service risk, breaks down DoS vulnerabilities into high-, medium-, and low-risk classes, and has recommendations for mitigations at each layer. -
Displaying Breaks - Building SaaS #72
In this episode, I worked to add breaks to the display of the week schedule. We had to update context to include the break information into the schedules. I refactored a method out of the calendar display code to make some reusable logic for handling breaks. The app needs to display breaks on the schedule and adjust what is displayed based on when the breaks are. I started with changing the background color of the break days. -
Episode 8 - Administering Your App
On this episode, we will focus on the built-in Django administrator’s site. We’ll see what it is, how you can configure it, and how you can customize it to serve your needs. Listen at djangoriffs.com. Last Episode On the last episode, we explored more about models and how to interact with data in your database. What Is The Django Admin? Django includes a web administrative interface that can help programmers and non-programmers alike. -
Training Interviewers
What’s the best way to train folks to conduct job interviews? I have a process I’ve used for about five years that seems to work well. It’s loosely based on the “see one, do one, teach one” methodology used by many medical schools. Here’s what I do: 1. Training I’ll spend about an hour covering the practice of interviewing: how to ask questions and follow-ups, take notes, correct for unconscious bias, handle difficult situations, etc. -
Is Django a Full Stack Framework?
The title of this post, "Is Django a Full Stack Framework?" is a question I receive often from new web developers. It's a very valid question so I wanted to … -
How To Keep Your Custom Form Fields DRY
When building a custom form which yields a group of incremental fields several times over, we often manually create each group like the following:class ExampleForm(forms.Form): first_name_1 = forms.CharField(required=False) last_name_1 = ... -
How to Unit Test a Django Management Command
This post is an adapted extract from my book Speed Up Your Django Tests, available now. When we write custom management commands, it’s easy to write integration tests for them with call_command(). This allows us to invoke the management command as it runs under manage.py, and retrieve the return code, standard output, and standard error. It’s great, but has some overhead, making our tests slower than necessary. If we have logic separated out of the command’s handle() method, it improves both readability and testability, as we can unit test it separately. Example Command Take this management command, that implements some book title normalization rules: from django.core.management.base import BaseCommand from django.db.transaction import atomic from example.core.models import Book class Command(BaseCommand): help = "Normalize all Book titles" def add_arguments(self, parser): parser.add_argument( "--write", action="store_true", default=False, help="Actually edit the database", ) @atomic def handle(self, *args, write, **kwargs): if not write: self.stdout.write("In dry run mode (--write not passed)") books = Book.objects.select_for_update() for book in books: book.title = self.normalize_title(book.title) if write: Book.objects.bulk_update(books, ["title"]) self.stdout.write(f"Updated {len(books)} book(s)") def normalize_title(self, title): if not title: return "Unknown" if title[0].islower(): title = title[0].upper() + title[1:] if title.endswith("."): title = title[:-1] title = title.replace("&", "and") return title (These is the same logic … -
VS Code: Automatically Organize Python Imports
In this quick tip, we'll see how to configure VS Code to automatically organize Python imports upon saving your source code files. VS Code: Automatically Organize Python Imports You can configure VS Code to automatically sort and organize Python imports upon saving files. First need to install the isort package system-wide using the following command: $ pipenv install isort --dev Open the settings using ⇧⌘P or Ctrl+Shift+P, next search for Preferences: Configure Language Specific Settings.... Press Enter and then search for Python. In the settings.json file that will be opened, add the following settings: "[python]": { "editor.codeActionsOnSave": { "source.organizeImports": true } } Now upon saving files with the .py extension, VS Code will automatically sort and organize the imports. -
Run your Python Unit Tests with GitHub Actions
In this tutorial, we'll learn how to automatically run your Python unit tests using GitHub Actions. We'll see how to set up a GitHub Actions workflow that install Python 3.6 inside a Ubuntu system along with our project's dependencies e.g. pytest and finnaly run the unit tests after pushing our code to a GitHub repository. Let's see how to automate running unit tests when making a commit and pushing your code to GitHub or when making a pull request. Thanks to GitHub Actions it's now easier than before without using any external services and they even provide a good free tier. This will allow you to spot the right commit(s) that broke your code. We'll be using Python 3, and we will be working in a virtual environment. This is a good practice for Python to isolate system packages from our project's package. Even if this is a small example but should be a practice that you need to always follow. Let's start by creating and activating a virtual environment for our project, by running the following commands: $ mkdir pytestexample $ cd pytestexample $ python3 -m venv .env This will create a virtual environment called .env in our project's … -
How to Delete Local/Remote Git Branches
If you have previously worked with Git for versioning your Angular code, there is a good chance that you had some situation where you wanted to delete a remote branch or multiple branches. This happens many times to developers, particularly in large projects. In this article, we'll learn: How to delete a local branch in your Git repository, How to delete a remote branch in Git, How to delete all Git branches which have been merged, How to remove all local branches not on remote, How to delete all your local Git branches except master. Before tackling how to delete a remote branch, we’ll first see how to delete a branch in the local Git repository. Note: Version control systems are an indispensable tool in modern web development that can help you solve many issues related to every task. Git is one of the most popular version control systems nowadays. Before we proceed to learn how to delete local and remote branches in Git, let's define what's a Git branch and the side effects of deleting branches. A branch in Git is a pointer to a commit. If you delete a branch, it deletes the pointer to the commit. This … -
Using Comments in JSON with Node.js and JavaScript Examples
In this article, we'll learn how to use comments in JSON files. We'll see workarounds and methods used by developers to add single-line and multiple-line comments to their JSON files, the external libraries and packages for stripping comments from your files before feeding them to the regular JSON.parse() method in JavaScript and Node.js and we'll also see simple JavaScript code for removing comments without external libraries. Finally, we'll see the alternative formats to JSON that support comments such as JSON5 and JSONC. JSON Doesn't Support Comments! As you might be aware of, JSON doesn't support comments! But as programmers, we are used to add comments so in this article, we'll see the possible ways that we have to use comments in our JSON files even if they are natively supported by the format. In fact, comments were not always missing in JSON but were removed later. This is the reason of removing comments from JSON as stated by Douglas Crockford. I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. JSON can be mostly needed if you use JSON for your configuration files even if JSON in … -
Removing Comments from JSON with Python
JSON doesn't permit comments by design. As explained by its creator Douglas Crockford. I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. But he also stated that you can use external or built-in tools to pre-parse JSON files and remove any comments before the actual parsing takes place. In this short article, we'll see how you can remove comments from JSON files using Python code. How to Read JSON Files with Python First, we need to be able to read JSON files in our Python code: import json with open('example.json') as json_file: data = json.load(json_file) print(data) How to Remove Comments from your JSON File There are various workarounds used by developers to add comments to JSON files generally. You can use JS-style comments (single-line // and multiline /* .. */) in your JSON files and pre-parse them with your Python code to remove the comments before reading them in the previous way: import json with open('data.json', 'r') as jsonfile: jsondata = ''.join(line for line in jsonfile if not line.startswith('//')) data = json.loads(jsondata) print(data) You can also use external packages such as: JSON-minify: A port of the … -
What happens when you run manage.py test?
This is a blog post version of the talk I gave at DjangoCon Australia 2020 today. There’s also the slides repository which contains the full example code. You run your tests with manage.py test. You know what happens inside your tests, since you write them. But how does the test runner work to execute them, and put the dots, E’s, and F’s on your screen? When you learn how Django middleware works, you unlock a huge number of use cases, such as changing cookies, setting global headers, and logging requests. Similarly, learning how your tests run will help you customize the process, for example loading tests in a different order, configuring test settings without a separate file, or blocking outgoing HTTP requests. In this post, we’ll make a vital customization of our test run’s output - we’ll swap the “dots and letters” default style to use emojis to represent test success, failure, etc: $ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). 💥❎❌⏭✅✅✅✳️ ... ---------------------------------------------------------------------- Ran 8 tests in 0.003s FAILED (failures=1, errors=1, skipped=1, expected failures=1, unexpected successes=1) Destroying test database for alias 'default'... But before we can write that, we need … -
Django Hosting & Deployment Options
[Django](https://www.djangoproject.com/) websites can be deployed on any number of hosting providers. The first choice is deciding whether to use a Platform-as-a-service (PaaS) option or a virtual private server (VPS). A … -
Django News - Django Security Release! - Sep 4th 2020
News Django security releases issued: 3.1.1, 3.0.10 and 2.2.16 Time to update your Django version! djangoproject.com Events Django Day 2020 - Sept 25th Djangonauts from in and around Denmark are meeting up for the second edition of Django Day, to be held on September 25th 2020. It will be a full day of talks, either to be experienced online -or- at our venue with safe social distancing. djangoday.dk Articles Django ORM if you already know SQL An illustrated guide to Django's ORM by drawing analogies to equivalent SQL statements. dev.to OneToOne Relationship Linking your user model to your custom profile model in Django. hashnode.dev Bonus Django Documentation Sites Links and brief descriptions of Classy Class-Based View/Forms/REST Framework which are vital additional documentation resources. adamj.eu Demystifying Django’s Magic Precious Ndubueze breaks down a default Django project one generated file and folder at a time. smashingmagazine.com Linux Commands for Developers A good introduction to basic Linux commands for developers. This is a nice refresher for developers of any skill level. dev.to Podcasts Running in Production - DataWellness DataWellness is a Django service that helps organizations stay safe and compliant, hosted on a single DigitalOcean server and up since 2016. runninginproduction.com Test & … -
Custom Form Validation - Building SaaS #71
In this episode, I added some custom checking to ensure that students may only be enrolled in a single grade level for a school year. We talked about form cleaning and wrote a for unit test to prove that the change worked. After that change, we switched to a template and wrote copy for when no progress reports are viewable for users. With the first issue, I needed to update a form that enrolls students. -
Bonus Django Documentation Sites
There are a few mini sites out there with “bonus” Django documentation. Here’s a list of the best ones I know of. Classy Class-Based Views Classy Class-Based Views is a class explorer for the class-based view (CBV) hierarchy in Django: If you’re struggling to figure out what’s going on in your CBV’s, this is a real boon for navigating them. It was created by Charles Denton and Marc Tamlyn. It seems to be a little unmaintained at current, but the information within should still be fairly accurate since Django’s CBV’s don’t change often. Whilst on the topic of CBV’s, I can’t help but mention django-vanilla-views: This is a library that provides a simpler CBV hierarchy, with a comparison against Django’s built-in one. It was created by Tom Christie and I help maintain it. Classy Django Forms Classy Django Forms is a similar class explorer for Django’s forms and form fields: It’s a project by Ana Balica, based on Classy Class-Based Views, and seems to be up to date with Django 3.0 at least. Template Tags and Filters Template Tags and Filters is a cheatsheet for Django’s template language: It was made this year so should be up to date with … -
Office Hours
Ask me professional questions in a small group Zoom meeting setting. Past topics of discussion have included: Code review! Attendees can share code with me, unless given permission I won't share with other attendees even though I will comment verbally on it. Project design and architecture Resolving bugs in code Career advice Managing tough job situations Resume and portfolio evaluation Next session is 10AM to Noon PST / 5PM-7PM UTC on Wednesday, September 2nd, 2020. Sign up now! -
Django Testing Tutorial
Testing is an important but often neglected part of any Django project. In this tutorial we'll review testing best practices and example code that can be applied to any Django … -
Authenticating Django PostgreSQL User in Multiple Docker Compose Environments
I’ve been building a Django project template using Docker Compose, PostgreSQL, and Nginx. Docker is a definite weak point for me, so I used an article from Michael Herman to set it up: Dockerizing Django with Postgres, Gunicorn, and Nginx. I made some additions to that tutorial – custom user model, re-organized config files – but I kept running into the same issue… Django Can’t Connect to Postgres When switching between development and production environments, Django could not connect to my postgres database: docker-compose up -d --build docker-compose exec web python manage.py migrate django.db.utils.OperationalError: FATAL: password authentication failed for user "" I had set up the same username for both the development and the production environment postgres services, but the passwords were different. For some reason, Docker Compose wasn’t re-configuring postgres with the new information when I switched containers. Temporary Fix I was able to avoid the problem with some help from the testdriven.io tutorial mentioned above: docker-compose down -v docker-compose -f docker-compose.prod.yml down -v The -v flag brings down all volumes, i.e. my postgres database. Then, when bringing the containers back up, Docker Compose would say, “I don’t have any volume called postgres_data. I better make one!” This would … -
Django and the N+1 Queries Problem
This is a cross-post from the Scout APM blog, where I occasionally write. I also maintain the Scout Python integration. The N+1 Queries Problem is a perennial database performance issue. It affects many ORM’s and custom SQL code, and Django’s ORM is not immune either. In this post, we’ll examine what the N+1 Queries Problem looks like in Django, some tools for fixing it, and most importantly some tools for detecting it. Naturally Scout is one of those tools, with its built-in N+1 Insights tool. We’ll cover: What Is the N+1 Queries Problem? N+1 Queries 2N+1 Queries NM+N+1 Queries Tools to Fix the N+1 Queries Problem select_related() prefetch_related() django-auto-prefetch Tools for Finding N+1 Query Problems django-debug-toolbar nplusone Scout APM What Is the N+1 Queries Problem? In a nutshell: code that loops over a list of results from one query, and then performs another query per result. Let’s look at a basic example and a couple of its natural extensions. N+1 Queries Say we had this code: books = Book.objects.order_by("title") for book in books: print(book.title, "by", book.author.name) This code uses print() for simplicity, but the problem exists in all other ways data might be accessed, such as in templates or views … -
Introducing Tight.ai - My First Desktop App
I just released a production-g...