Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Save a Django Query to the Database
I found a StackOverflow question on saving a Django query to the database, but I was left super unclear on what to do. There’s all this talk about… -
Save a Django Query to the Database
I found a StackOverflow question on saving a Django query to the database, but I was left super unclear on what to do. There’s all this talk about pickling and serialization that I’m sure makes a ton of sense to someone smarter than me. The current answer is old, however, and in 2022, I found another solution: turning a dict into JSON. Plus, I found a way to make it work with my htmx live search, allowing me to view the results of my query on the front end of my site (read: pretty) to double-check that things look okay before saving. I’ll show you what I did below. I believe pickling still works, so at the end I will show some more thoughts there. models.py - example database structure class Transaction(models.Model): id = models.CharField(max_length=24, primary_key=True) date = models.DateField(null=False) amount = models.IntegerField(null=False) info = models.CharField() account = models.ForiegnKey(Account, on_delete=models.SET_NULL, null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=False, default=None) class Account(models.Model): name = models.CharField() email = models.EmailField() class Category(models.Model): name = models.CharField(unique=True) class Rule(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=False, null=True, default=None) criteria = models.JSONField(default=dict) # this will hold our query My models store financial transactions, the category the transaction fits into (e.g., … -
Django News - DjangoCon Europe 2022 - Jan 28th 2022
News Announcing DjangoCon Europe 2022 DjangoCon Europe 2022 is back again and it’s going to be five full days of talks, tutorials, and sprints September 21-25, 2022. djangoproject.com Django Styleguide Survey HackSoft is running a survey on current Django style usage which will be used to update its open source Django Styleguide. hacksoft.io Trends and Insights Trends and Insights for January So much happens on social media that doesn't always get covered in traditional articles, and we wanted to experiment with an occasional Trends and Insights section. Let us know if you like the idea and what you think. We might make it a more permanent part of our newsletter if it's well-received. 🐍 CPython's main branch now compiles to WebAssembly, which means that Python will run natively in your web browser. Check out Katie Bell's "How to run Python in the browser" talk from LCA 2022. 🥚 Dustin Ingram shared some packaging insights that, as of December 2021, less than 1% of all uploading PyPI packages include .egg files. Python eggs are effectively deprecated. 🧪 Jamie Matthews shared a nice PyQuery snippet that makes testing for exact text easier in a reply thread about Django Template tips, tricks, and … -
Ordering Existing Models - Building SaaS with Python and Django #125
In this episode, we built out a customer requested feature of adding order of grade levels within the school year of my homeschool app. This will allow users to change the display of crucial pages within the app. -
Ordering Existing Models - Building SaaS #125
In this episode, we built out a customer requested feature of adding order of grade levels within the school year of my homeschool app. This will allow users to change the display of crucial pages within the app. -
How to Set Up Source Maps with Django
Source maps are files that map your minified CSS or JavaScript back to the original code. They allow you to use your browser’s development tools to debug minified code as if it were the original. In this post we’ll look at how source maps fit into Django’s static files infrastructure, including a couple recent changes I made to Django to better support them. We’ll look at using a JavaScript source map, but everything applies equally to CSS source maps. Alrighty, let’s dig in. Directory Layout Let’s look at an example project using source maps to see how they fit into Django’s infrastructure. This project demonstrates a static file setup that works well for most projects. The project has three directories for “static files” with different roles, all in the root of repository: frontend/, which contains the source CSS and JavaScript files. Django doesn’t use this directory at all. Frontend tools, like bundlers, should process the source files in frontend/ and place output files in the next directory, static/. This provides a clear “hand off”. static/, which contains static files for Django to manage. This is in the STATICFILES_DIRS setting: STATICFILES_DIRS = [BASE_DIR / "static"] static_root/, which is created by Django’s … -
For hire
As I write this it’s the evening of January 23, 2022. A little over two weeks ago I gave notice at my now-former employer, and as of two days ago I am officially on the job market. If you already know me and are interested in talking about an opportunity, please get in touch. Or if you want to know a bit more first, read on… Who I am It’s a bit tricky to pin down when … Read full entry -
Django Rest Framework authentication: the easy way
In this tutorial you'll learn how to implement Django Rest Framework authentication in your web application by leveraging the built-in Django session framework. This approach is way simpler (and secure) than other popular methods such as JWT, and has only one requirement: your frontend (think Vue.js, React, ...) and your backend should be served by the same domain. I created an example project on GitHub you can use to follow along with this tutorial. Table of Contents Why you should avoid JWT for Django Rest Framework authentication Django Rest Framework settings Django Rest Framework authentication endpoint Test authentication using HTTPie A new endpoint to retrieve the user profile Test the user profile endpoint using HTTPie Conclusions Why you should avoid JWT for Django Rest Framework authentication JWT (Json Web Token) is a very popular method to provide authentication in APIs. If you are developing a modern web application with Vue.js or React as the frontend and Django Rest Framework as the backend, there is an high probability that you are considering JWT as the best method to implement authentication. The reality is that JWT is just one method, and unfortunately not the simpler, nor the most reliable. JWT is not … -
Four Tips for Writing Better Go APIs
Go is a really powerful programming language that allows you to write concurrent code that is still easy to understand. But designing APIs can be hard, even for seasoned Go programmers. When designing APIs for libraries and applications in Go it's important to keep in mind the strengths of the language to make your APIs easier to use and avoid pitfalls like goroutine leaks. With that in mind, here are a few common issues I see often with Go APIs and some tips for how to make them better. ## Don't Take APIs Out of Context The context package is a very powerful package that takes some get[...] -
Zip Archive HTTP Response - Building SaaS with Python and Django #124
In this episode, we continued to build the PDF reporting feature. The focus on the stream was on building the zip archive file as the HTTP response. This will be the container for future PDF reports. I also started the setup for the weasyprint PDF package. -
Django News - Migrating WordPress to Wagtail - Jan 21st 2022
News WordPress to Wagtail CMS Migration Kit There are many reasons to migrate your WordPress site to Wagtail. Rest assured the migration doesn't need to be painful. wagtail.io Python 3.10.2, 3.9.10, and 3.11.0a4 are now available The releases you’re looking at were all cursed in some way. What a way to start 2022! python.org Wagtail Release 2.15.2 Bugfix with one security (CVE-2022-21683) update. github.com Events PyCascades 2022 Schedule PyCascades is remote on February 5-6, 2022. The schedule of talks is now available. pycascades.com Sponsored Link Stay secure with CodeStasis Keep your old Django install secure with our backported patches fixing security vulnerabilities and data loss bugs. Django 1.8 and up available now at www.codestasis.com. Get notified when 1.6 and 1.7 are released. CodeStasis is free for personal use and a paid subscription for businesses. codestasis.com Articles Why is Exposing the Docker Socket a Really Bad Idea? An exploration of why Django sockets should not be exposed in most cases and a real-world use case where the Docker socket needs to be mounted in your container. quarkslab.com Faster API development with django-dataclasses A description of features contained in the new django-dataclasses library and why it was created. medium.com Tutorials How to … -
Zip Archive HTTP Response - Building SaaS #124
In this episode, we continued to build the PDF reporting feature. The focus on the stream was on building the zip archive file as the HTTP response. This will be the container for future PDF reports. I also started the setup for the weasyprint PDF package. -
A Problem with Duplicated Mutable Constants
Here’s a small problem I’ve seen where several modules share versions of the same “constant” variable. It came up in the context of a Django project with multiple settings files, but it could happen in different contexts. Imagine you have two submodules defining API_CONFIG as a “constant” dictinoary. The development submodule should copy the value in base, but use a different value for the "rate_limit" key. You have example/base.py which looks like: API_CONFIG = { # ... "rate_limit": "10/m", # ... } …and example/development.py: from example.base import API_CONFIG API_CONFIG["rate_limit"] = "100/m" By importing from base, the development module doesn’t need to completely redefine API_CONFIG. Great - the redundant repetition is reduced. But can you see the flaw in this approach? The problem is that API_CONFIG is the same dict in both modules. The change in development “leaks” back to base: In [1]: from example import base In [2]: base.API_CONFIG["rate_limit"] Out[2]: '10/m' In [3]: from example import development In [4]: development.API_CONFIG["rate_limit"] Out[4]: '100/m' In [5]: base.API_CONFIG["rate_limit"] Out[5]: '100/m' Eek! This happens because Python variables are only names for underlying objects. Pointing another name to the same variable does not create a copy. If this is surprising, Ned Batchelder’s Python Names and … -
Django Best Practices: Template Structure
There are two main ways to organize your template structure in Django: the default app-level way and a custom project-level approach. ## Option 1: App Level By default the Django … -
Django at UC Berkeley - Mohammed Shamma and Matthew Newton
Mohammed on TwitterMatthew on TwitterBerkeley’s Nobel laureatesGive @BerkeleyhtmxSupport the ShowThis podcast does not have any ads or sponsors. To support the show, please consider purchasing a book, signing up for Button, or reading the Django News newsletter. -
On Receiving the Malcolm Tredinnick Award
In December I was awarded the Malcolm Tredinnick Award. This is an annual award, selected by nominations from anyone in the Django community. I’m incredibly honoured to have been selected, joining a fine list of past recipients. I’ve been inspired by every one of them. Malcolm’s Legacy Malcolm Tredinnick was an active member of the Django community from its early days. He joined as a core developer from the early days of the project, especially focusing on the ORM. He contributed until his sudden death in 2013. The Django Software Foundation founded the prize in his honour later that year. I don’t believe I ever interacted with Malcolm. I was less than a year into my Django journey when he passed away, before I engaged with the community. But I have encountered his traces on the web, especially in Django’s ticket tracker and the django-developers mailing list. Malcolm gave many talks about Python, Django, and other programming adventures. I’ve watched a few on YouTube. I particularly enjoyed his DjangoCon 2012 talk “The Dungeon Master's guide to Django's ORM”, which explains the history of the ORM code, relevant to this day. A Personal Note I’m very grateful for receiving the prize … -
Go Fast With Django
In the last Understand Django article, we learned about commands. Commands are the way to execute scripts that interact with your Django app. With this article, we’re going to dig into performance. How do you make your Django site faster? Keep reading to find out. From Browser To DjangoURLs Lead The WayViews On ViewsTemplates For User InterfacesUser Interaction With FormsStore Data With ModelsAdminister All The ThingsAnatomy Of An ApplicationUser AuthenticationMiddleware Do You Go? -
Book Review: Powerful (Patty McCord)
Patty McCord was Netflix’s first head of HR and a member of its executive team for 14 years. She (along with Reed Hastings, Netflix’s founder and CEO). She’s probably best known as the co-author (with Hastings) of Netflix’s famous Culture Deck, a 125-slide deck that lays out Netflix’s unusual culture. Powerful is a deep examination of that culture and its ramifications. It’s one of the better dissections of what “culture” really is and how it works. I recommend it to anyone in a position to influence company culture. You may or may not want to mimic Netflix, but thinking through which parts of Netflix’s culture you do and don’t want to mimic is an excellent exercise – it certainly was for me. -
How to Add a Favicon to Your Django Site
Your site’s favicon appears in the browser tab, and is a key way to brand your site. Setting up a favicon is a simple task, but once you start considering vendor-specific icons, it becomes more complicated. In this post we’ll cover: what the HTML specification says about favicons browser support two simple ways to serve a favicon from Django the vast world of vendor-specific icons generating and serving a bunch of vendor-specific icons with RealFaviconGenerator Alright, let’s get into it. To Specify an Icon, or Not The HTML specification defines two ways to specify a site’s icon (source). First, you can add one or more <link>s with rel=icon to your page’s <head>. The browser will then pick between these and use the most appropriate (that works): <link rel=icon href=favicon-16.png sizes=16x16 type=image/png> <link rel=icon href=favicon-32.png sizes=32x32 type=image/png> The browser may pick based on size or advertised file type. Second, if you don’t list any such <link>s, the browser will automatically request /favicon.ico and use that, if it’s a supported image. .ico is the file suffix for Microsoft Windows icons, but you don’t need to use this file type. Browsers always obey the Content-Type header, so you can serve other image types. … -
Security 101: Securing file downloads
One of the most common way to handle user uploaded content is persisting the data to disk, or uploading it to an object store like AWS S3. Serving the content back to the user (or others) often is handled by returning the URL to the file. What is oftentimes missing is proper authentication and authorization, as engineers seem to believe no one will leak URLs, run enumeration attacks or simply try random strings. This is not just a data breach waiting to happen, it is one happening way too often. In this post we will look at three options how this can be solved. The examples which you can find in the demo repository are written in Python, using Django. All three should work just fine in basically any modern language and framework used for web development, and with most web servers and reverse proxies such as Nginx. I am using Caddy, as the configuration is concise and simple to follow. For all examples you can upload a file via Django Admin and browse and download the files by visiting /. All examples only check if the user is authenticated. In a real system you will most likely want to … -
Security 101: Securing file downloads
Security 101: Securing file downloads One of the most common way to handle user uploaded content is persisting the data to disk, or uploading it to an object store like AWS S3. Serving the content back to the user (or others) often is handled by returning the URL to the file. What is oftentimes missing is proper authentication and authorization, as engineers seem to believe no one will leak URLs, run enumeration attacks or simply try random strings. This is not just a data breach waiting to happen, it is one happening way too often. In this post we will look at three options how this can be solved. The examples which you can find in the demo repository are written in Python, using Django. All three should work just fine in basically any modern language and framework used for web development, and with most web servers and reverse proxies such as Nginx. I am using Caddy, as the configuration is concise and simple to follow. For all examples you can upload a file via Django Admin and browse and download the files by visiting /. All examples only check if the user is authenticated. In a real system you … -
Set up EditorConfig for Your Django Project
This post is an adapted extract from my book Boost Your Django DX, available now. The “tabs versus spaces” war is scheduled to rage on until the heat death of the universe. And whilst the Python ecosystem is firmly in the “spaces” camp, there remain numerous other text formatting options. Inconsistent text formatting between team members can lead to unnecessary editing and even bugs. So it’s best to normalize text formatting in your projects. EditorConfig is a standard for text editor configuration. It’s built-in to many text editors, such as PyCharm and GitHub’s web editor. For other text editors, you need to install a small plugin, available for nearly every text editor under the sun. To set up EditorConfig for your project, create a file called .editorconfig the root of your repository. Note the . prefix, which makes the file hidden on Unix systems. The .editorconfig file uses INI file syntax, as parsed by Python’s configparser module. Here is a .editorconfig file suitable for most Django projects: # http://editorconfig.org root = true [*] charset = utf-8 end_of_line = lf indent_style = space indent_size = 2 trim_trailing_whitespace = true insert_final_newline = true [*.py] indent_size = 4 Here’s what this configuration does: … -
Meet the New Owners of Caktus
Nearly every week, I receive an email or two from a third party expressing interest in buying Caktus. As a matter of habit, I don't open them, let alone respond. Most are scattershot, venture capital firms looking for Software-as-a-Service companies (which Caktus is not). But when an employee approached me in 2018 expressing an interest in making Caktus employee-owned, I listened. Since 2018, we've been working to identify what employee ownership might look like at Caktus. The employee who originally brought up the idea has since moved on, but the idea took hold. We formed an eight member steering committee made up of interested (and skeptical) people from a cross section of the wider team. The steering committee was charged with crafting a proposal to present to the entire company. The effort also involved the assistance of an outside non-profit organization that assists with employee ownership transitions, as well as our existing legal and accounting advisors. In the summer of 2020, the steering committee presented the proposal to the rest of the company, and determined that we had the buy-in necessary to move forward. Since that time, we've been working with our advisors to finalize the legal and accounting aspects … -
Django News - Python is #1 Programming Language - Jan 14th 2022
News Python Programming Language of the Year 2021 Python is #1!!! tiobe.com Sphinx and Markdown around the world in 2021 Read the Docs is adding more Markdown features. readthedocs.com Django Discord Server Django now has an approved Discord Server to hang out on for anyone who likes Discord. discord.com Sponsored Link Error monitoring for Django Developers. Track and debug exceptions in record time so you can get back to doing what you love. honeybadger.io Articles Five Tips For a Healthier Postgres Database in the New Year A year-end wrap-up of 5 things you can do for a healthier Postgres database next year. crunchydata.com Removing Python 3.6 Support from My Packages by Adam Johnson Python 3.6 reached its end of life on the 23rd December and Adam describes how he removed it from all his third-party packages using the myrepos tool. adamj.eu How I build a feature While not directly Django-related, Simon Willison steps us through his development and workflow for creating new software features from creating an issue, writing release notes, and then telling the world about it. simonwillison.net Design Articles Grid for layout, Flexbox for components While not a new post, this article helped me wrap my head around … -
How to setup Django with Pytest on GitHub Actions
Someone recently asked me When is a good time to get automated testing setup on a new Django project? The answer is "now". There are other good times, but now is best. In this post I'll briefly make my case for why, and show you an example of a minimal …