Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django on a production server
Is your Django project ready for production? Follow these guides to bring your Django project on a production server! There are many good tutorials out there for learning Django and developing projects locally. But I think that simple tutorials for production deployment is somewhat lacking. In this guide I'll try to fill this gap a little bit. 😉 In the last months I wrote some tutorials that will show you how to bring your Django project on production. Here is a summary of each tutorial. 1. Django NGINX: deploy your Django project on a production server This tutorial will give you the basics on deployment using the NGINX webserver and uWSGI application server. Django NGINX: deploy your Django project on a production server Read more... 2. How to deploy a Django project in 15 minutes with Ansible This tutorial will make a step further and will show you how to leverage the power of Ansible to automate all the steps needed for a production deployment. How to deploy a Django project in 15 minutes with Ansible Read more... 3. Bitbucket Pipelines and Ansible: Continuous delivery for your Django project If you are using Bitbucket you can automate the deployment when … -
Remodeling Data Relationships - Building SaaS #55
In this episode, we’re remodeling! I changed the model relationship between GradeLevel and Course from a ForeignKey (1 to many) to a ManyToManyField. We talked through the change and started fixing all the tests that broke. After explaining the change that I wanted to make and why I want to make it, I explained how a foreign key and many to many relationship at the database level. Once we had the conceptual foundation in place, I started with the documentation. -
Django Security - Markus Holtermann
Weekly Django Chat NewsletterMarkus Holtermann personal siteDjango TeamsDEP 0010: New governance for the Django projectA Month in the Life of a DSF Board MemberDjango Announce Google GroupDjangoCICrateIO - Database for IoT ScaleDjangoCon Europe 2018 - On the Look-Out For Your DataLogging RethoughtBeeWareDep 8: Gathering Django usage analyticsSHAMELESS PLUGSLearnDjango - Free tutorials and premium books -
How to setup Celery with Django
In this Django Celery tutorial, I will talk about how to setup Celery with Django and some basic concepts which can help you better understand Celery. -
How to setup Celery with Django
In this Django Celery tutorial, I will talk about how to setup Celery with Django and some basic concepts which can help you better understand Celery. -
How to Move a Django Model to Another App
In my latest article for RealPython I share three ways to tackle one of the most challenging tasks involving Django migrations: moving a model from one Django app to another. The article covers some exotic migration operations and many of the built-in migration CLI commands such sqlmigrate, showmigrations and sqlsequencereset. In the article I also demonstrate important migrations concepts such as reversible migrations, migration plans and introspection. Read "How to Move a Django Model to Another App" on RealPython ≫ How to Move a Django Model to Another App -
Variations on the death of Python 2
On April 20th, 2020, a release manager named Benjamin Peterson smashed the “publish” button on Python 2.7.18. The Python 2 release series had already reached the end of its upstream support from the Python core team at the start of the year. I don’t know for certain, but I assumed the timing of the actual final package was meant to occur during PyCon (which, until a global pandemic struck, was scheduled for mid-April), possibly so … Read full entry -
User Interaction With Forms
In the previous Understand Django article, we saw how Django templates work to produce a user interface. That’s fine if you only need need to display a user interface, but what do you do if you need your site to interact with users? You use Django’s form system! In this article, we’ll focus on how to work with web forms using the Django form system. Web Forms 101 Before we can dive into how Django handles forms, we need to have an understanding of HTML forms in general. -
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.