Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Caching in Django
This article first provides an overview of Django's caching framework and then shows how to cache a Django view using both Memcached and Redis. -
Why You Should Document Your Tests
Some projects have the policy that all tests must have an explanatory comment – including all of mine. At first, I found that baffling. If that’s you right now, this article is for you. -
Book Announcement: Speed Up Your Django Tests
At the start of March I started writing a blog post called “How to Speed Up Your Django Tests.” Before I knew it, the outline alone was 4,000 words! I realized writing it up would be a major undertaking. As lockdown arrived, I found the time to write it all up. So, I’m delighted to announce my new e-book, coming May 18… Speed Up Your Django Tests! It’s a practical guide to making your Django project’s tests faster. It has many tips and tricks that apply to all projects, big and small. And it covers the two most popular test runners: Django’s test framework and pytest. Reducing test run time is the easiest and safest way to increase your speed of delivery. And it’s an organic way of increasing team happiness! The content is based on my 8 years of experience with tests on Django projects. I’ve sped up many projects’ test suites, improved Django’s own testing framework, and created several pytest plugins. It contains 13 chapters: Introduction - Opening notes, how to use the book. Toolbox - A tour of the various tools you can use to change how your tests run. Measure! - The importance of profiling, with … -
Using webpack with Django: it's not easy as you think
These days I'm seeing new tutorials on using webpack with Django popping up. Like: Django and Webpack - Static Files Managed Efficiently Using Webpack with Django: no plugins required! I don't mean to bash on them, but, the problem with the approaches showed there is that they work for smaller JavaScript applications. I mean tiny applications. Imagine instead a medium-size React/Vue application with some state management solution like Redux or Vuex. Imagine also a bunch of JavaScript libraries needed by this application, and imagine a JavaScript bundle resulting from this app that goes over 200KB. Let's see what I mean. webpack and Django without code splitting A typical webpack configuration for Django configured to produce a JavaScript bundle in the static folder looks like the following: const path = require("path"); module.exports = { entry: "./index.js", output: { path: path.resolve(__dirname, "../static/custom_webpack_conf_2/js"), filename: "[name].js" }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } } ] } }; With this configuration, given an entry point at ./index.js, webpack produces the corresponding bundle in ../static/custom_webpack_conf_2/js. In the Django template you'll load the bundle as: {% load static %} <!DOCTYPE html> <html lang="en"> <body> <h1>Hello Django!</h1> <div id="root"></div> </body> … -
Serverless Django with PostgreSQL with Cloud SQL and Cloud Run
Below is a reference guide for... -
Django News - Issue 21 - May 1st 2020
News PyCharm & DSF Campaign 2020 Results The recent JetBrains PyCharm campaign raised $40k for the Django Software Foundation. djangoproject.com Articles New Features in Python 3.9 You Should Know About While Python 3.9 is not scheduled for release until October 2020, you can still see what new features, improvements and fixes we can expect and look forward to. dev.to Using Webpack with Django: no plugins required! If you have struggled to configure Django and Webpack to work together then this article is for you. pascalw.me Packaging without setup.py Learn how to migrate your setup.py scripts to Poetry. pgjones.dev Django Testing Cheat Sheet A cheat-sheet of common testing patterns and best practices in Django applications. valentinog.com Videos PyCon 2020 - Optimize Python & Django apps with Postgres superpowers Learn Postgres superpowers to help optimize performance of Python and Django apps, using a sample Django application which runs on Azure Database for PostgreSQL. youtu.be PyCon 2020 - Deploying Django on Serverless Infrastructure Learn how to deploy Django on Serverless Infrastructure using Google Cloud. youtube.com Podcasts Django Chat #61 - Practices of the Python Pro with Dane Hillard Dane is the author of a new book, Practices of the Python Pro. The discussion … -
Testing an Interactive Voice Response System With Python and Pytest
Following my previous article on how to build an Interactive Voice Response (IVR) system with Twilio, Python and Django, in this follow-up tutorial I show how to write automated tests for this system. It can be very challenging to test a system that rely heavily on a third party service such as Twilio. In this article, I show how to organize your code in a way that would isolate your bushiness logic and make it easier to test separately. The article demonstrate useful testing patterns using Django's RequestFactory, unittest.mock, Pytest fixtures, build-in django-pytest and many more. Source Code The source code for this article and the previous one can be found here. Read "Testing a Twilio Interactive Voice Response System With Python and Pytest" on the Twilio blog ≫ Building an IVR System with Django and Twilio -
User Testing Feedback - Building SaaS #54
In this episode, we worked on issues found from a round of user testing. I talked about how I did user testing with my customer, then started to tackle the usability issues that she identified. We’re taking a break from building the onboarding flow so that we can take some time to address feedback from user testing with my customer. I started the stream by explaining how I set up user testing and what I got out of the experience. -
Practices of the Python Pro - Dane Hillard
Weekly Django Chat NewsletterDane Hillard personal siteITHAKAPractices of the Python ProInstallPython3.comAn Effective Python Environment: Making Yourself at HomePyOhio 2019 - Adopt-a-pytestDjangoCon US 2018 - Serverless Django with ZappaDjangoCon US 2019 - Using a custom template loader at scaleTriplicate custom fontEffective Python Testing with PytestReceive 40% off Dane’s book and those from Manning using poddjango20. -
Working with request.data in Django REST framework
Django REST generic views are amazing. It's hard to justify writing a flow-complete view by hand unless you're doing something so easy that doesn't require validation or other stuff. Even then why leaving the enlightened path? There are situations however where you want to change request.data a bit in a generic view, and things will get tricky ... The problem: an example with CreateAPIView CreateAPIView is a concrete view for handling the POST/return response lifecycle in a RESTful API. It accepts JSON POST requests. After installing and configuring DRF all you need to start accepting requests is a subclass of CreateAPIView with a serializer. Example: # library/views/api.py from rest_framework.generics import CreateAPIView from library.serializers import ContactSerializer class ContactCreateAPI(CreateAPIView): serializer_class = ContactSerializer Here ContactSerializer is a DRF model serializer for a simple model. Here's the serializer: from rest_framework.serializers import ModelSerializer from .models import Contact class ContactSerializer(ModelSerializer): class Meta: model = Contact fields = ("first_name", "last_name", "message") And here's the model: from django.db import models class Contact(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) message = models.TextField(max_length=400) def __str__(self): return f"{self.first_name} {self.last_name}" It's all bells and whistles until the frontend sends an object with exactly the same properties found in the serializer. What I … -
Generic, functional based and class based views in Django REST Framework
Django-Rest-Framework(DRF) supports three different types of views. They are Function Based Views Class Based Views / Generic Views ViewSets Based on the developer convenience developer can choose the type of view. Function based views(FBV): Our view should return the response as per the standards of the django rest framework (Response but not reggular HttpResponse). Django REST provides a set of decorators that will check whether the view returning the correct Response or not. Django REST provides the following decorators api_view, renderer_classes, parser_classes, authentication_classes, throttle_classes, permission_classes, detail_route, list_route @api_view: It converts the function based view into a subclass of API view. @renderer_classes: It takes an iterable set of renderer classes which helps in creating response to a request with various media types. @parser_classes: It takes an iterable set of parser classes which allows REST to accept requests with different various media types. @authentication_classes: It takes an iterable set of authentication classes that will allow REST authenticate the request. @throttle_classes: It takes an iterable set of throttle classes that will limit number of requests per user in a specific amount of time. @permission_classes: It takes an iterable set of permission classes that allows REST to check whether user allowed to take the requested resource or not. @detail_route: … -
Continuously Deploying Django to AWS EC2 with Docker and GitLab
In this tutorial, we'll look at how to configure GitLab CI to continuously deploy a Django and Docker application to AWS EC2. -
Roll Your Own Class-Based Views in Django
Function-based views are typically easy for beginners to understand. Just create a function that receives a request object and returns a response object. But class-based views (CBV) tend to cause more confusion. Most of the functionality lives in out-of-sight base views and mixins, so using a CBV usually means overwriting a handful of class attributes and methods. When I started using CBVs, I had no mental model how they worked. The result was lots of googling and trying to make sense of Django source code. Over time I learned how views fit together, but the journey there was tedious and at times confusing. What This Tutorial Is This tutorial aims to conceptually connect function-based views with class-based views. More specifically, we’ll build views that provide a JSON-only, REST API endpoint for a /very/ simple Django application. By starting with something familiar, we can refactor the code into custom class-based views. The result is a base view class with mixins and generics, similar in design to the classes used by Django and Django-Rest-Framework. What This Tutorial Isn’t We aren’t building a perfect reproduction of Django’s class based views. Our views don’t need nearly as much functionality, and we don’t even address … -
Secure your Django API from DDoS attacks with NGINX and fail2ban
Hello everyone! Last week our Django API, hosted on an Amazon EC2 server was attacked by a botnet farm, which took our services down for almost the entire weekend. I’m not going to lie, it was a very stressful situation, but at the same time we learned a lot about how to secure our server from future DDoS attacks. For our solution we are using the rate-limiting functionality from NGINX and fail2ban, a program that bans external APIs when they break a certain set of rules. Let’s start! NGINX configuration In NGINX is simple, we just need to configure the rate-limiting on our website level. We are using Django with the Django REST framework, so we went with a configuration of 5 requests per second (5r/s) with extra bursts of 5 requests. This works fine with Django, but you might need to tweak it for your configuration. This allows a total of 10 requests (5 processing and 5 in queue) before our API returns a 503 server error limit_req_zone $binary_remote_addr zone=one:20m rate=5r/s; server { limit_req zone=one burst=5 nodelay; # ... } Let me explain what is going on here: First, we are setting up the limit_req_zone. The $binary_remote_addr specifies that … -
My mom was always right | Rant on social media
My mom always hated social media. My bother and I always made fun of her because she was always late to all the news. Her main reason against social media was “why would I want everyone to know what I’m doing? And why should I care what they are doing?”. I didn’t understand at the time, but now I do. I remember when I was 13 years old social media started ramping up. I created a MySpace account to go with the flow. I won’t lie, I liked MySpace a lot: creating a website that “defined me”, sharing my music, posting funny pictures and checking my friends' profiles. It all seemed pretty cool and innovative. Then it came to Facebook, where you couldn’t create your own site or share music players like in MySpace, but you had a wall and your friends could leave messages on your wall! How cool was that? You could share pictures, thoughts, opinions, and your friends didn’t have to go to your profile to check it out: Facebook had a feed with all your friends' posts, so there was no need to visit their profile just to see what they were doing. It sounded very … -
My mom was always right | Rant on social media
My mom always hated social media. My bother and I always made fun of her because she was always late to all the news. Her main reason against social media was “why would I want everyone to know what I’m doing? And why should I care what they are doing?”. I didn’t understand at the time, but now I do. I remember when I was 13 years old social media started ramping up. I created a MySpace account to go with the flow. I won’t lie, I liked MySpace a lot: creating a website that “defined me”, sharing my music, posting funny pictures and checking my friends' profiles. It all seemed pretty cool and innovative. Then it came to Facebook, where you couldn’t create your own site or share music players like in MySpace, but you had a wall and your friends could leave messages on your wall! How cool was that? You could share pictures, thoughts, opinions, and your friends didn’t have to go to your profile to check it out: Facebook had a feed with all your friends' posts, so there was no need to visit their profile just to see what they were doing. It sounded very … -
Managing Secrets with Vault and Consul
This post looks at how to set up and use Hashicorp's Vault and Consul to securely store and manage secrets. -
Django News - Issue 20 - Apr 24th 2020
Articles Beginner Sourdough: Does anything really matter? urllib3 creator and maintainer Andrey Petrov deep dives and shares his thoughts on a subject that's been on everyone's mind lately, a guide on how to read sourdough recipes. 🍞 medium.com Oops! Removing Secrets from Django Project in Docker Have you ever accidentally committed a SECRET_KEY or another sensitive setting to a git repository and wondered how to remove it? startcodingnow.com Sync Data to and From Google Sheets with django-gsheets The django-gsheets Django app makes two-way data sync from models to Google Sheets simple. meanpug.com Podcasts Django Chat #60 - Advanced Deployment with Katie McLaughlin Katie is a Developer Advocate for Google and regular conference speaker. Discussion covers advanced deployment techniques and tools such as Google Cloud Run, relational vs non-relational databases, Terraform, and more. djangochat.com Tutorials Effective Python Testing With Pytest A wonderful tutorial on pytest benefits, approach, and how to apply to any Python project. realpython.com Handling Periodic Tasks in Django with Celery and Docker A detailed tutorial on using Django, Celery, and Redis together. testdriven.io How To Create a URL Shortener with Django and GraphQL Create a non-relational GraphQL backend for a URL shortener: a service that takes any URL … -
Introducing django-gsheets, an easy way to sync to and from Google Sheets
Django ships with a great admin interface, it's one of the top reasons the framework is chosen. Often though, the need (or "need") arises to view and manipulate model data in a spreadsheet instead of the web admin. Rather than go through the traditional ETL process of exporting this data to a CSV to be loaded into a Google Sheet (or visa versa), django-gsheets makes syncing data between Google Sheets and your Django app as simple as executing python manage.py syncgsheets.Two-way data sync from Django to Google SheetsHere are some common reasons you might want two-way sync in your app.performing running audits of data quality in a table or set of tablesproviding an interface for external users to upload structured data (e.g. think mechanical turk)giving non-technical users an efficient way to scrub data in bulkUsing django-gsheets in your projectGetting started with django-gsheets should be a familiar task for the Django developer. We start by installing the necessary dependencies then add some configuration to our settings.py to integrate the app in our project. Note: this guide is basically a long form version of the repo README, so if you're just itching to get started you should probably stop reading and start … -
More Onboarding Goodness - Building SaaS #53
In this episode, we continued with onboarding. I added unit tests for the new form and explained how foreign keys are wired through in CreateView. Then we marched on to the next template in the flow. In the last stream, we set all the context data for the view that shows the form to create a grade level for the school. With the context in place, and the form structure set, I added the form class that will create the GradeLevel record. -
Oops! Removing Secrets from Django Project in Docker
So you’ve been frantic as you try to fix a bug. You get lost in the work and totally forget where you are. All of a sudden… SUCCESS!… -
Advanced Deployment - Katie McLaughlin
Weekly Django Chat NewsletterTwitter @glasntKatie's talksPyCon 2020 - What is deployment, anyway? (video)PyCon 2020 - Tutorial: Deploying Django on Serverless Infrastructureih-aas repo Google Cloud SQLGoogle Cloud RunCloud Run buttondjango-demo-app-unicodexAja Hammerly thread on Developer Advocates being busy without conferencesDjangoCon Europe 2016 - Building a Non-Relational Backend for the ORM - Adam Alton (video) (djangae)"Every production setup will be a little bit different" - djangoproject.com -
Google Cloud CLI & SDK Setup
Google Cloud has a number of a... -
Oops! Removing Secrets from Django Project in Docker
So you’ve been frantic as you try to fix a bug. You get lost in the work and totally forget where you are. All of a sudden… SUCCESS! It works! Amazing. But oh no, you just put your secrets into a tracked file. What to do, what to do… Project Overview So I’ve been saying “you”, but I really mean “me”. Here’s a short summary of my project, then we’ll get into how I fixed it. Web app coded in Python Using the Django web framework Using Docker with a Dockerfile and docker-compose.yml for containerization Deployed to Heroku Had a problem serving static files on Heroku and not locally, so I implemented an Amazon S3 bucket for remote file storage, which requires secrets! Up until this point, I’ve tracked my docker-compose.yml file so that if I want to work on this project on another computer, it will be easy to clone and get going. But I’m hosting this code on GitHub and may share it some day, so I don’t want secrets available. Fixing Django’s SECRET_KEY My docker-compose.yml file has my Django SECRET_KEY inside it. When prepping to deploy to Heroku, all I did was generate a new key and … -
Handling Periodic Tasks in Django with Celery and Docker
This post looks at how to manage periodic tasks with Django, Celery, and Docker.