Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Elm & Django #1
Here is a simple solution to run Elm code within a Django template. This could be used to handle the full frontend or just to embed a "widget" - like a search bar - via Elm. -
Elm & Django #1
Here is a simple solution to run Elm code within a Django template. This could be used to handle the full frontend or just to embed a "widget" - like a search bar - via Elm. -
Caktus Blog Best of 2017
With 2017 now over, we highlight the top 17 posts published or updated on the Caktus blog this year. Have you read them all? Using Amazon S3 to Store your Django Site’s Static and Media Files: Our most popular blog post was updated in September 2017 with new information. Learn how to use Amazon S3 to serve static and media files and improve site performance. A Production-ready Dockerfile for Your Python/Django App: Docker provides a solid way to containerize an app. This blog post includes a Dockerfile ready for your use plus instructions on how to use it in a project. Python Type Annotations: Type annotation support in Python helps developers avoid errors. Read this post for a quick overview on how to use them. Digging Into Django QuerySets: Learn how to use the Django shell with an example app to perform queries. Hosting Django Sites on Amazon Elastic Beanstalk: We use AWS Elastic Beanstalk for deploys and autoscaling. This post introduces the basics and how to use it with Python. SubTests are the Best: Good tests are important to good code, but what makes a good test? Three factors are detailed in this post, which was also presented as … -
Create a Mobile Application with Ionic 3, Angular 5 and Django Rest Framework
In this tutorial, we are going to learn, step by step how to create a mobile application with an Ionic 3/Angular 5 front-end and a Python back-end. We'll be using Django and Django Rest Framework to build a simple REST API. The app we'll be creating is a simple product tracker that can be used to keep track of the quantities of the products you have in stock. You'll be able to create products, increment and decrement their quantities. In nutshell, we need to: create the Django project create the Django application design and create the database model(s) migrate the database generate the admin web interface to create, read, update and delete the database records create a super user generate a browsable and documented REST API with Django Rest Framework generate the Ionic 3 project create an Angular 5 CRUD service to interface with the REST API create an Ionic page to create and update products create an Ionic page to read the products add a method to delete products Introduction to Django Django is a Python-based web framework that encourages rapid development. It's used by many web developers create web applications using the Python language. Django has a plethora … -
Django multitenancy using Postgres Row Level Security
Quite some time ago, I did some experiments in [using Postgres Row Level Security (RLS) from within Django](http://schinckel.net/2015/12/07/row-level-security-in-postgres-and-django/). It occurred to me that this philosophy could be used to model a multi-tenant application. The main big problem with [django-boardinghouse](http://django-boardinghouse.readthedocs.io) is that you have to apply migrations to multiple schemata. With many tenants, this can take a long time. It's not easy to do this in a way that would be conducive to having limited downtime. On the other hand, RLS means that the database restricts which rows of specific tables need to be shown in a given circumstance. Normally, examples of RLS show this by using a different user, but this is not necessary. In fact, in most modern web applications, a single database user is used for all connections. This has some big benefits (in that a connection to the database can belong to a pool, and be shared by different requests). Luckily, there are other ways to have RLS applied. One method is to use Postgres' session variables. This is outlined quite well in [Application users vs. Row Level Security](https://blog.2ndquadrant.com/application-users-vs-row-level-security/). I'm going just use simple session variables, as the facility for doing this will be encapsulated, and based … -
Building Modern Django Web Applications with React and Django Rest Framework
In nutshell, in this tutorial we'll look at how to build a modern (SPA: Single Page Application) CRUD web application using Django and React.js (instead of Django built-in templates engine). We'll use Django Rest Framework to build an example API, react-router-dom for routing the front-end app, Axios for making HTTP calls (GET, POST, PUT and DELETE etc.) to the Rest API endpoints, Redux for managing the app's global state and finally Webpack to bundle the assets This tutorial will cover how to serve the React app using the Django server and how to allow the React app to communicate with the Django server over its Rest API endpoints When building a modern web application with tools such as Django and React in our case, React will take care of rendering the view layer of your app's architecure and Django will be used for communicating with the database and exposing a CRUD REST API. You can have completly separate front-end and back-end or you can also make Django serve the first page where the React app will be mounted (we'll follow this second approach in this tutorial). The communication between React and Django will be made using HTTP/Ajax requests to the … -
Building Modern Django Web Applications with React and Django Rest Framework
In nutshell, in this tutorial we'll look at how to build a modern (SPA: Single Page Application) CRUD web application using Django and React.js (instead of Django built-in templates engine). We'll use Django Rest Framework to build an example API, react-router-dom for routing the front-end app, Axios for making HTTP calls (GET, POST, PUT and DELETE etc.) to the Rest API endpoints, Redux for managing the app's global state and finally Webpack to bundle the assets This tutorial will cover how to serve the React app using the Django server and how to allow the React app to communicate with the Django server over its Rest API endpoints When building a modern web application with tools such as Django and React in our case, React will take care of rendering the view layer of your app's architecure and Django will be used for communicating with the database and exposing a CRUD REST API. You can have completly separate front-end and back-end or you can also make Django serve the first page where the React app will be mounted (we'll follow this second approach in this tutorial). The communication between React and Django will be made using HTTP/Ajax requests to the … -
REST API Basics with the Django REST Framework
This post is the same as the p... -
Building Modern Web Apps with Python, Django Rest Framework and Angular 2+
In this tutorial we are going to learn how to get started building modern web applications with Python, Django and Django Rest Framework as the back-end stack and the new Google Framework, Angular 2+, to build JavaScript client side applications, as the front-end technology. We'll see how to integrate both frameworks in the development and the production environments and how to use the Angular HTTP module to make API calls or Ajax requests to our REST API back-end. This tutorial is using the old Angular HTTP client for making HTTP calls. This module is deprecated in Angular 5 and will be replaced by the new Angular HttpClient module available in Angular 4.3+ which comes with many new features such as the HTTP interceptors. The two modules have the same API interface so you should be able to easily migrate to the new one. In future tutorials we will be using HttpClient so stay tuned! The Angular CLI is a command line utility which allows you to quickly generate and build Angular 2+ apps without the hassle of WebPack configuration. The CLI takes care of the configuration and let you focus on build your next Angular app. It's a really great … -
Building APIs with Django and GraphQL
This tutorial will introduce you to GraphQL with Python, Django and Graphene. We'll see how to create a simple Django project to demonstrate how to build an API server based on GraphQL (instead of REST) then we'll see how to use graphiql_django, an interface for testing GraphQL queries and mutations before building your front-end application, to send GraphQL Queries (for getting data) and Mutations (for posting and updating data). In this part we'll be dealing with building the backend. In the next tutorials we will see how to use frameworks and libraries such as Angular and React to build a front-end application that consumes and updates our GraphQL server and advanced use cases such as user authentication, permissions and Relay Make sure to follow me on twitter (@techiediaries) to be notified once the next tutorial parts are ready. GraphQL is a modern API standard for building Web APIs, invented and used internally by Facebook for its native mobile applications then later open sourced. GraphQL provides a better, powerful and flexible alternative to REST. Before we dive into GraphQL concepts, let's understand what's REST: REST stands for Representational State Transfer and it's an architectural pattern for designing client/server distributed systems. Unlike … -
Building Django HTTP APIs with GraphQL and Graphene
This tutorial will introduce you to GraphQL with Python, Django and Graphene. We'll see how to create a simple Django project to demonstrate how to build an API server based on GraphQL (instead of REST) then we'll see how to use graphiql_django, an interface for testing GraphQL queries and mutations before building your front-end application, to send GraphQL Queries (for getting data) and Mutations (for posting and updating data). In this part we'll be dealing with building the backend. In the next tutorials we will see how to use frameworks and libraries such as Angular and React to build a front-end application that consumes and updates our GraphQL server and advanced use cases such as user authentication, permissions and Relay Make sure to follow me on twitter (@techiediaries) to be notified once the next tutorial parts are ready. GraphQL is a modern API standard for building Web APIs, invented and used internally by Facebook for its native mobile applications then later open sourced. GraphQL provides a better, powerful and flexible alternative to REST. Before we dive into GraphQL concepts, let's understand what's REST: REST stands for Representational State Transfer and it's an architectural pattern for designing client/server distributed systems. Unlike … -
Building APIs with Django, GraphQL and Graphene
This tutorial will introduce you to GraphQL with Python, Django and Graphene. We'll see how to create a simple Django project to demonstrate how to build an API server based on GraphQL (instead of REST) then we'll see how to use graphiql_django, an interface for testing GraphQL queries and mutations before building your front-end application, to send GraphQL Queries (for getting data) and Mutations (for posting and updating data). In this part we'll be dealing with building the backend. In the next tutorials we will see how to use frameworks and libraries such as Angular and React to build a front-end application that consumes and updates our GraphQL server and advanced use cases such as user authentication, permissions and Relay Make sure to follow me on twitter (@techiediaries) to be notified once the next tutorial parts are ready. GraphQL is a modern API standard for building Web APIs, invented and used internally by Facebook for its native mobile applications then later open sourced. GraphQL provides a better, powerful and flexible alternative to REST. Before we dive into GraphQL concepts, let's understand what's REST: REST stands for Representational State Transfer and it's an architectural pattern for designing client/server distributed systems. Unlike … -
Django Quiz 2017
Yesterday evening I gave a quiz at the London Django Meetup Group for the second year running. Here it is so you can do it at home (no cheating!). Answers are at the bottom. Part 1: Trivia 1. What species is Django’s unofficial spirit animal? Pegasus Unicorn Pony Seal Dolphin Elephant 2. Djangocon EU this year was in… Bologna Genoa Venice Florence 3. What does LTS stand for? Long Tail Support Long Term Support Life Time Support Life Term Support 4. What does WSGI stand for? Web Socket Gateway Interface Web Server Gateway Interface Web Server Gated Interface WebS GuardIan 5. What does ACID stand for? Atomicity Consistency Integrity Durability Atomicity Concurrency Isolation Durability Atomicity Consistency Isolation Durability All Carefully Inserted Data 6. When was the first commit on Django? One point for year, one for month, one for day 7. When was the first commit in Python? One point for year, one for month, one for day 8. What is the name of the current Django fellow? One point for first name, one for last Part 2: Coding with Django 1. What’s the import for the new Django 2.0 URL syntax? from django.paths import url from django.urls import path … -
Django REST Framework Authentication by Example with JSON Web Tokens (JWT)
Introduction Django Rest Framework provides multiple mechanisms for authenticating users, in case you are new to this concept then simply put: authentication is the process of verifying the identity of users, while authorization is identifying if the user has authorized access to some server resource. In this tutorial, we are going to see what's the available mechanisms, in DRF, to authenticate users? What is the difference between DRF built-in token-based authentication system and JWT authentication? And how to add JSON Web Tokens authentication to Django Rest Framework? Different Ways to Authenticate Users? The general process of authenticating a user is done by simply checking if any user information or credentials are attached to an incoming (from the client) request. DRF has already three mechanisms to authenticate users. Let's look at each one of them: Basic authentication: It's very easy to setup but it's only recommended for testing purposes not for production. It's implemented in rest_framework.authentication.BasicAuthentication class and works by base64 encoding the user login information i.e the user's name and the password then attach them to an HTTP Authorization Header (can then be retrieved from request.META.HTTP_ AUTHORIZATION). Session based authentication: The traditional authentication mechanism and the default one used by … -
From MySQL to PostgreSQL
In this article I will guide you through the steps I had to take to migrate Django projects from MySQL to PostgreSQL. MySQL database has proven to be a good start for small and medium scale projects. It is known and used widely and has good documentation. Also there are great clients for easy management, like phpMyAdmin (web), HeidiSQL (windows), or Sequel Pro (macOS). However, in my professional life there were unfortunate moments, when databases from different projects crashed because of large queries or file system errors. Also I had database integrity errors which appeared in the MySQL databases throughout years because of different bugs at the application level. When one thinks about scaling a project, they have to choose something more suitable. It should be something that is fast, reliable, and well supports ANSI standards of relational databases. Something that most top Django developers use. And the database of choice for most professionals happens to be PostgreSQL. PostgreSQL enables using several vendor-specific features that were not possible with MySQL, e.g. multidimensional arrays, JSON fields, key-value pair fields, special case-insensitive text fields, range fields, special indexes, full-text search, etc. For a newcomer, the best client that I know - pgAdmin … -
Really simple Django view function timer decorator
I use this sometimes to get insight into how long some view functions take. Perhaps you find it useful too: def view_function_timer(prefix='', writeto=print): def decorator(func): @functools.wraps(func) def inner(*args, **kwargs): try: t0 = time.time() return func(*args, **kwargs) finally: t1 = time.time() writeto( 'View Function', '({})'.format(prefix) if prefix else '', func.__name__, args[1:], 'Took', '{:.2f}ms'.format(1000 * (t1 - t0)), args[0].build_absolute_uri(), ) return inner return decorator And to use it: from wherever import view_function_timer @view_function_timer() def homepage(request, thing): ... return render(request, template, context) And then it prints something like this: View Function homepage ('valueofthing',) Took 23.22ms http://localhost:8000/home/valueofthing It's useful when you don't want a full-blown solution to measure all view functions with a middleware or something. It can be useful also to see how a cache decorator might work: from django.views.decorators.cache import cache_page from wherever import view_function_timer @view_function_timer('possibly cached') @cache_page(60 * 60 * 2) # two hours cache @view_function_timer('not cached') def homepage(request, thing): ... return render(request, template, context) That way you can trace that, with tail -f or something, to see how/if the cacheing decorator works. There are many better solutions that are more robust but might be a bigger investment. For example, I would recommend markus which, if you don't have a statsd … -
Django version 2.0 // A Few Key Features
I'll be updating this post fro... -
Accessing Model's/Object's Verbose Name in Django Template
Let's say you have a model: from django.db import models class Snippet(models.Model): .... class Meta: verbose_name = 'Snippet' verbose_name_plural = 'Snippets' And you want to print model's verbose name in a Django template. Try to do it as {{ object._meta.verbose_name }} and you will fail - Django template won ... Read now -
My rules for releasing open source software
My rules for releasing open source software I maintain and help maintain quite a few Open Source Python packages. Possibly well-known packages include django-debug-toolbar, django-ckeditor, django-mptt, and FeinCMS resp. feincms3. Open source development used to stress me greatly. I was always worrying whether the code is polished enough, whether I didn’t introduce new bugs and whether the documentation is sufficient. These days I still think about these things, but I do not worry as much as I used to. The reason for this are the following principles: A fully passing test suite on Travis CI is a sufficient quality guarantee for a release. Do not worry about release notes, but always keep the CHANGELOG up to date. Put out patch releases even for the smallest bugfixes and feature additions (as long as they are backwards compatible). Nobody wants to wait for the next big release, it always takes longer than intended. Good enough is perfection. -
Django 2.0 Window expressions tutorial
Django 2.0 was released recently and among the most exciting things for me is support for Window expressions, which allows adding an OVER clause to querysets. We will use Window expressions to analyze the commits data to the Django repo. So what is an over clause? An over clause is of this format SELECT depname, empno, salary, avg(salary) OVER (PARTITION BY depname) FROM empsalary; Compare this to a similar GROUP BY statement SELECT depname, avg(salary) FROM empsalary GROUP BY depname; The difference is a GROUP BY has as many rows as grouping elements, here number of depname. An over clause adds the the aggregated result to each row of the select. Postgres documentation says, "A window function performs a calculation across a set of table rows that are somehow related to the current row. This is comparable to the type of calculation that can be done with an aggregate function. But unlike regular aggregate functions, use of a window function does not cause rows to become grouped into a single output row — the rows retain their separate identities. Behind the scenes, the window function is able to access more than just the current row of the query result." This … -
Django 2.0 Windows expressions tutorial
Django 2.0 was released recently and among the most exciting things for me is support for Window expressions, which allows adding an OVER clause to querysets. We will use Window expressions to analyze the commits data to the Django repo. So what is an over clause? An over clause is of this format SELECT depname, empno, salary, avg(salary) OVER (PARTITION BY depname) FROM empsalary; Compare this to a similar GROUP BY statement SELECT depname, avg(salary) FROM empsalary GROUP BY depname; The difference is a GROUP BY has as many rows as grouping elements, here number of depname. An over clause adds the the aggregated result to each row of the select. Postgres documentation says, "A window function performs a calculation across a set of table rows that are somehow related to the current row. This is comparable to the type of calculation that can be done with an aggregate function. But unlike regular aggregate functions, use of a window function does not cause rows to become grouped into a single output row — the rows retain their separate identities. Behind the scenes, the window function is able to access more than just the current row of the query result." This … -
Container Runtimes Part 1: An Introduction to Container Runtimes
One of the terms you hear a lot when dealing with containers is "container runtime". "Container runtime" can have different meanings to different people so it's no wonder that it's such a confusing and vaguely understood term, even within the container community. This post is the first in a series that will be in four parts: 1. Part 1: Intro to Container Runtimes: why are they so confusing? 2. Part 2: Deep Dive into Low-Level Runtimes 3. Part 3: Deep Dive into High-Level Runtimes 4. Part 4: Kubernetes Runtimes and the CRI This post will explain what container runtimes are and w[...] -
Container Runtimes Part 1: An Introduction to Container Runtimes
One of the terms you hear a lot when dealing with containers is "container runtime". "Container runtime" can have different meanings to different people so it's no wonder that it's such a confusing and vaguely understood term, even within the container community. This post is the first in a series that will be in four parts: 1. Part 1: Intro to Container Runtimes: why are they so confusing? 2. Part 2: Deep Dive into Low-Level Runtimes 3. Part 3: Deep Dive into High-Level Runtimes 4. Part 4: Kubernetes Runtimes and the CRI This post will explain what container runtimes are and w[...] -
Caktus is Excited about Django 2.0
Did you know Django 2.0 is coming soon? The development team at Caktus knows and we’re excited! You should be excited too if you work with or depend on Django. Here’s what our Cakti have been saying about the recently-released 2.0 beta. What are Cakti Excited About? Django first supported Python 3 with the release of version 1.5 back in February 2014. Adoption of Python 3 has only grown since then and we’re ready for the milestone that 2.0 marks: dropping support for Python 2. Legacy projects that aren’t ready to make the jump can still enjoy the long-term support of Django 1.11 on Python 2, of course. With the removal of Python 2 support, a lot of Django’s internals have been simplified and cleaned up, no longer needing to support both major variants of Python. We’ve put a lot of work into moving our own projects forward to Python 3 and it’s great to see the wider Django community moving forward, too. In more concrete changes, some Caktus devs are enthused by transitions Django is making away from positional arguments, which can be error-prone. Among the changes are the removal of optional positional arguments from form fields, removal of … -
Setup & Install Ionic
Ionic is a framework for build...