Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Updates to Love
-
How to Use Celery and RabbitMQ with Django
Celery is an asynchronous task queue based on distributed message passing. Task queues are used as a strategy to distribute the workload between threads/machines. In this tutorial I will explain how to install and setup Celery + RabbitMQ to execute asynchronous in a Django application. To work with Celery, we also need to install RabbitMQ because Celery requires an external solution to send and receive messages. Those solutions are called message brokers. Currently, Celery supports RabbitMQ, Redis, and Amazon SQS as message broker solutions. Table of Contents Why Should I Use Celery? Installation Installing RabbitMQ on Ubuntu 16.04 Installing RabbitMQ on Mac Installing RabbitMQ on Windows and Other OSs Celery Basic Setup Creating Our First Celery Task Starting The Worker Process Managing The Worker Process in Production with Supervisord Further Reading Why Should I Use Celery? Web applications works with request and response cycles. When the user access a certain URL of your application the Web browser send a request to your server. Django receive this request and do something with it. Usually it involves executing queries in the database, processing data. While Django does his thing and process the request, the user have to wait. When Django finalize its … -
Monorepo structure for Django & React Applications
Hello! Today I will guide you through setting up React application with Django! Let's get started! First thing is where I place my javascript application? Should it be in another repository? Or maybe Django should use webpack to render js? I decided to use pattern called monorepo. What does it … -
How to Render Django Form Manually
Dealing with user input is a very common task in any Web application or Web site. The standard way to do it is through HTML forms, where the user input some data, submit it to the server, and then the server does something with it. Now, the chances are that you might have already heard that quote: “All input is evil!” I don’t know who said that first, but it was very well said. Truth is, every input in your application is a door, a potential attack vector. So you better secure all doors! To make your life easier, and to give you some peace of mind, Django offers a very rich, reliable and secure forms API. And you should definitely use it, no matter how simple your HTML form is. Managing user input, form processing is a fairly complex task, because it involves interacting with many layers of your application. It have to access the database; clean, validate, transform, and guarantee the integrity of the data; sometimes it needs to interact with multiple models, communicate human readable error messages, and then finally it also have to translate all the Python code that represents your models into HTML inputs. In … -
Demystifying encodings — part 2
As we saw in part 1 of this series, each program reads stuff from input and writes stuff to output. Whenever it reads strings of characters in the input, these strings are encoded in a certain encoding such as UTF-8. The program must decode these strings into an internal representation. When writing to the output, the program encodes strings from its internal representation to an encoding such as UTF-8. What this internal representation is is usually not our concern. For example, in Python versions earlier than 3.3, the internal representation is either UCS-2 or UCS-4, depending on how Python was compiled. In Python 3.3 or later, the internal representation is more complicated and described in PEP 393. But these details are rarely of interest; what matters is that a program must be able to communicate with other programs via its input/output, and for this to work properly the programs must agree on an external representation. Whenever you see “appétit” rendered as “appétit” it usually means that two programs did not agree on the encoding of the external representation; for example, that one program sent UTF-8 to its output, and another program read this output as its input, thinking it was … -
Django Patterns: Fat Models and `cached_property`
One of my favorite patterns in Django is the combination of "fat" models and cached_property from django.utils.functional. Fat models are a general MVC concept which encourages pushing logic into methods on your Model layer rather than the Controller ("view" in Django parlance). This has a lot of benefits. It helps maintain the DRY (Don't Repeat Yourself) principle by making common logic easy to find/reuse and makes it easy to break the logic down into small testable units. One problem with this approach is that as you break down your logic into smaller more reusable units, you may find yourself using them multiple times within a single response. If your methods are particularly resource intensive, it will become an unnecessary performance hit. A common place you find this is in Django tempaltes with patterns like this: {% if item.top_ten_reviews %} <ul> {% for review in item.top_ten_reviews %} ... This will call the top_ten_reviews method twice. If that method is making database calls, you've now doubled them. Enter cached_property. This decorator will cache the results of a method for the duration of the request and return it as a property when called again. This technique is known as memoization. Let's look at … -
Django Patterns: Fat Models and cached_property
One of my favorite patterns in Django is the combination of "fat" models and cached_property from django.utils.functional. Fat models are a general MVC concept which encourages pushing logic into methods on your Model layer rather than the Controller ("view" in Django parlance). This has a lot of benefits. It helps maintain the DRY (Don't Repeat Yourself) principle by making common logic easy to find/reuse and makes it easy to break the logic down into small testable units. One problem with this approach is that as you break down your logic into smaller more reusable units, you may find yourself using them multiple times within a single response. If your methods are particularly resource intensive, it will become an unnecessary performance hit. A common place you find this is in Django templates with patterns like this: {% if item.top_ten_reviews %} <ul> {% for review in item.top_ten_reviews %} ... This will call the top_ten_reviews method twice. If that method is making database calls, you've now doubled them. Enter cached_property. This decorator will cache the results of a method for the duration of the request and return it as a property when called again. This technique is known as memoization. Let's look at … -
Large File Uploads with Amazon S3 + Django
****In Development**** This... -
ShipIt Day Recap Q3 2017
Caktus recently held the Q3 2017 ShipIt Day. Each quarter, employees take a step back from business as usual and take advantage of time to work on personal projects or otherwise develop skills. This quarter, we enjoyed fresh crêpes while working on a variety of projects, from coloring books to Alexa skills. -
Django Tips #21 Using The Redirects App
Django comes with a few optional apps that can easily be installed. One of those apps is the Redirects App, which is particularly useful in the cases where you want to update some existing URLs without compromising your Website SEO or in any case avoid 404 errors. It basically works by creating a table in the database with two columns, old_path and new_path. Every time your Website raises a 404 error, the Redirects App will intercept the response and check this particular table for a match. If the requested URL is found in the column old_path, instead of raising the 404 error, it will redirect the user to the new_path returning a 301 code (Moved Permanently). Alright, so let’s see how it works in practice. Installation The Django Redirects App requires the sites framework to be installed. You can install them by adding the apps to your project’s INSTALLED_APPS: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.redirects', ] Set a SITE_ID so the sites framework works properly. settings.py SITE_ID = 1 Now, add the redirects middleware to the MIDDLEWARE configuration: settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.redirects.middleware.RedirectFallbackMiddleware', ] Make sure you … -
Make Django Rest Framework and Axios Work Together Nicely
This is a solution to the problem I encountered while marrying Django Rest Framework powered API and Axios JS HTTP client: Axios issues GET requests with multi-value parameters in a bit different way than Django expects. When you create your API with Django Rest Framework, it expects multi-value GET parameters ... Read now -
A Minimal Django Application
In this article I want to explore some of the basic concepts of Django, setting up a minimal web application to get a deeper understanding of how Django works under the hoods. An important disclaimer before we start, that’s not a tutorial about how to start a Django application, it’s more of an exploratory experiment for learning purpose. Introduction If you are reading this article, the chances are that you already know that Django is a Web framework written in Python. But that’s an abstract definition. In practice, Django is a Python package that lives inside the site-packages directory of your current Python installation. That means it lives alongside with other Python packages, such as Requests, Pillow and NumPy. A simple way to verify a Django installation is importing it in a Python shell: >>> import django >>> print(django.get_version()) 1.11.4 But the way we interact with Django is a little bit different than the way we interact with other Python packages. Usually we don’t import it directly into our Python programs to make use of its resources. When we first start learning Django, we are taught that we should start a new project using the django-admin command-line utility by executing … -
Fastest *local* cache backend possible for Django
I did another couple of benchmarks of different cache backends in Django. This is an extension/update on Fastest cache backend possible for Django published a couple of months ago. This benchmarking isn't as elaborate as the last one. Fewer tests and fewer variables. I have another app where I use a lot of caching. This web application will run its cache server on the same virtual machine. So no separation of cache server and web head(s). Just one Django server talking to localhost:11211 (memcached's default port) and localhost:6379 (Redis's default port). Also in this benchmark, the keys were slightly smaller. To simulate my applications "realistic needs" I made the benchmark fall on roughly 80% cache hits and 20% cache misses. The cache keys were 1 to 3 characters long and the cache values lists of strings always 30 items long (e.g. len(['abc', 'def', 'cba', ... , 'cab']) == 30). Also, in this benchmark I was too lazy to test all different parsers, serializers and compressors that django-redis supports. I only test python-memcached==1.58 versus django-redis==4.8.0 versus django-redis==4.8.0 && msgpack-python==0.4.8. The results are quite "boring". There's basically not enough difference to matter. Config Average Median Compared to fastest memcache 4.51s 3.90s 100% … -
Ask Vitor #4: WordPress or Self-Made Blog?
Aviral Tiwari asks: Is this blog made through Django or some blog engine like WordPress? Answer First of all, thanks Aviral for the great question! Short answer is: Jekyll + Django. Now, if you are interested in a little bit of the history of this blog and the technology stack behind it, keep reading! This blog is powered by Jekyll, a static site generator written in Ruby. All the pages, all the HTML you see is managed by Jekyll. But at some point this year I had to create a small API using Django to provide a few services and enhance the user experience. So, it’s a little bit of a Frankenstein code. The reason why I picked Jekyll in the beginning was simply because I had no intention to write on regular basis and honestly I did not expect the blog to grow as much as it did. Right now, the blog receives roughly 130,000 visits every month and it have been such a great experience – writing articles, interacting with the readers, reading comments, starting discussions. Anyway, Jekyll was a very convenient option, because you can host it using GitHub pages. So, all I needed was a domain … -
How to Setup Amazon S3 in a Django Project
In this tutorial you will learn how to use the Amazon S3 service to handle static assets and the user uploaded files, that is, the media assets. First, I will cover the basic concepts, installation and configuration. Then you will find three sections covering: Working with static assets only Working with static and media assets Mixing public assets and private assets Dependencies You will need to install two Python libraries: boto3 django-storages The boto3 library is a public API client to access the Amazon Web Services (AWS) resources, such as the Amazon S3. It’s an official distribution maintained by Amazon. The django-storages is an open-source library to manage storage backends like Dropbox, OneDrive and Amazon S3. It’s very convenient, as it plugs in the built-in Django storage backend API. In other words, it will make you life easier, as it won’t drastically change how you interact with the static/media assets. We will only need to add a few configuration parameters and it will do all the hard work for us. Amazon S3 Setup Before we get to the Django part, let’s set up the S3 part. We will need to create a user that have access to manage our S3 … -
Episode #1 - Brian Michael Riley
Do you like riding a bike? If ... -
Django, Virtualenv, & Python .gitignore File
We use `.gitignore` files ofte... -
Django, GraphQL & React - part two
In this post, I will guide you through setting up GraphQL with Django. Let's get started! I will use a library called graphene-django. It will help a lot and allow me to get the job done instead of writing boilerplate code. I decided I will have 3 django applications: actors … -
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 identifying a logged in user, 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 DRF available mechanisms to authenticate users, what is the difference between DRF built in token based auth system and JWT auth and then how to add JSON Web Tokens authentication to Django Rest Framework. How to Authenticate a User? 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, lets look at each one of them: Basic Authentication: It's very easy to setup but 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 username and the password and attach them to an HTTP Authorization Header (can then be retrieved from request.META.HTTP _ AUTHORIZATION). Session Based Authentication: The traditional authentication mechanism and default one used by … -
Install Django on Linux Ubuntu
# Install Django & Virtualenv ... -
Find static files defined in django-pipeline but not found
If you're reading this you're probably familiar with how, in django-pipeline, you define bundles of static files to be combined and served. If you're not familiar with django-pipeline it's unlike this'll be of much help. The Challenge (aka. the pitfall) So you specify bundles by creating things in your settings.py something like this: PIPELINE = { 'STYLESHEETS': { 'colors': { 'source_filenames': ( 'css/core.css', 'css/colors/*.css', 'css/layers.css' ), 'output_filename': 'css/colors.css', 'extra_context': { 'media': 'screen,projection', }, }, }, 'JAVASCRIPT': { 'stats': { 'source_filenames': ( 'js/jquery.js', 'js/d3.js', 'js/collections/*.js', 'js/aplication.js', ), 'output_filename': 'js/stats.js', } } } You do a bit more configuration and now, when you run ./manage.py collectstatic --noinput Django and django-pipeline will gather up all static files from all Django apps installed, then start post processing then and doing things like concatenating them into one file and doing stuff like minification etc. The problem is, if you look at the example snippet above, there's a typo. Instead of js/application.js it's accidentally js/aplication.js. Oh noes!! What's sad is it that nobody will notice (running ./manage.py collectstatic will exit with a 0). At least not unless you do some careful manual reviewing. Perhaps you will notice later, when you've pushed the site to prod, that … -
Two Scoops of Django Birthday Giveaway
Today is a special day. You see, the latest fantasy book I co-authored, Coldest Spring (3rd in the Ambria series), is out AND it's my birthday. In honor of of these occasions, the first book of the series, Darkest Autumn, for 0.99 cents on Amazon. Plus, I'm doing a Python-related giveaway. The Giveaway: There’s a python programming easter egg in the book. One of the characters mentions the elegance of Python. The first person who tells me in the comments below the name of the father and grandfather of that character gets an autographed Two Scoops of Django 1.11 book shipping anywhere in the world. Finally, if you want to give me a truly special present for my birthday, please review any or all of my books on Amazon. Positive or negative, every review makes a difference. The positive stuff feeds my already inflated ego, and the negative stuff tells me what I need to do in order to improve. Two Scoops of Django 1.11 Ambria 1: Darkest Autumn (Just $0.99 for the rest of July 2017!) Ambria 2: Brightest Winter Ambria 3: Coldest Spring -
Two Scoops of Django Birthday Giveaway
Today is a special day. You see, the latest fantasy book I co-authored, Coldest Spring (3rd in the Ambria series), is out AND it's my birthday. In honor of of these occasions, the first book of the series, Darkest Autumn, for 0.99 cents on Amazon. Plus, I'm doing a Python-related giveaway. The Giveaway: There's a python programming easter egg in the book. One of the characters mentions the elegance of Python. The first person who tells me in the comments below the name of the father and grandfather of that character gets an autographed Two Scoops of Django 1.11 book shipping anywhere in the world. Finally, if you want to give me a truly special present for my birthday, please review any or all of my books on Amazon. Positive or negative, every review makes a difference. The positive stuff feeds my already inflated ego, and the negative stuff tells me what I need to do in order to improve. Two Scoops of Django 1.11 Ambria 1: Darkest Autumn (Just \$0.99 for the rest of July 2017!) Ambria 2: Brightest Winter Ambria 3: Coldest Spring Updates July 24th 3pm: A commenter by the name of @lingot answered first and they'll … -
Is Django the Right Fit for your Project?
You need a website. You may have done some searches, and come back overwhelmed and empty-handed, having found hosting providers offering services that may have sounded familiar (“WordPress”) and ones that may have sounded like a foreign language (“cPanel”). You may have considered hiring someone to build your website, and gotten conflicting answers about what you need and what it would cost. You may have also heard about Django, but you’re not sure how it it fits into the picture and whether or not it’s the right fit for your project. This is common, because there are many different types of websites out there. To help answer the question of whether Django is the right fit for your project, let’s take a look at the landscape. -
Organizing Django Girls Recife
In Brazil, women are the majority in schools and universities and represent 60% of the people who have a university degree. Despite this, in STEM, they represent only 20% of the quantitative. This scenario is present not only in Brazil but all over the world. In technological areas, it’s no different. IT is still a mostly male world. It was with th