Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Aymeric Augustin
Aymeric personal siteFractal Ideas blogAymeric on Githubdjango-sesamedjango-sequenceswebsocketsSHAMELESS PLUGSLearnDjango - Free tutorials and premium books -
What's New in Django 3.1
Django 3.1 will be released in early August 2020 and comes a number of major new features and many minor improvements including asynchronous views and middleware support, asynchronous tests, JSONField … -
How to save Base64 encoded image to Django ImageField?
I had to create an API that had to accept an image in Base64 encoded format and save it to Django image field, which requires an image file. So today I learned how to do this. Step 1: B64 to PIL The first step will be to convert this B64 image to an image file in memory, I will be using Pillow for this. You can install Pillow using this bash command. pip install pillow Make sure you have pip installed. If you’re using Linux or Mac OS, then you might have to use pip3 instead of pip. But I’m using virtual env, so who cares. after that, write this function. import base64 import io from PIL import Image def decodeDesignImage(data): try: data = base64.b64decode(data.encode('UTF-8')) buf = io.BytesIO(data) img = Image.open(buf) return img except: return None This function will return a PIL image if the B64 data is valid, or it will return None. Step 2: PIL to Djnago ImageField After getting the PIL image, wrote a function that will take this PIL image, convert it into a JPEG file buffer and then inserted it to Database instance using InMemoryUploadedFile sources: InMemoryUploadedFile What is InMemoryUploadedFile? This is basically a representation … -
How to save Base64 encoded image to Django ImageField?
In this blog, I will show you how to convert B64 encoded image to Django ImageField object. -
Too many Invalid HTTP_HOST header exception errors
Have you deployed an application to production? Are you getting too many, seemingly random Invalid HTTP_HOST header exception errors? Background I have recently deployed a Django app: served via gunicorn/Nginx onto an AWS Lightsail instance with a CloudFlare certificate for https/SSL (followed this answer on StackOverflow for configuring it) Following deployment I had a barrage of Invalid HTTP_HOST header error emails. Every. Single. Day. I looked at the Nginx configuration. But it looked identical to other configurations I have in production. Configurations that do not have this kind of error. The Nginx server block looks like: upstream dbr_project { server unix:/home/ubuntu/[..]/gunicorn.sock fail_timeout=0; } server { listen 80 default_server; listen [::]:80 default_server; server_name subdomain.example.com; if ($http_x_forwarded_proto = "http") { return 301 https://$server_name$request_uri; } ... } On further inspection, these exceptions were being caused by bots. Example user agent strings: HTTP_USER_AGENT = 'Mozilla/5.0 (compatible; Nimbostratus-Bot/v1.3.2; http://cloudsystemnetworks.com)' HTTP_USER_AGENT = 'masscan/1.0 (https://github.com/robertdavidgraham/masscan)' So the cause looks external. And the “dirty” fix I resorted to is to stop reporting this class of error. Fix I’ve followed this answer on StackOverflow to stop reporting, or “suppress”, this error. My previous LOGGING config (which I stripped down to a bare minimum for this post) looked like: 1 … -
Django Testing Toolbox
What are the tools that I use to test a Django app? Let’s find out! You might say I’m test obsessed. I like having very high automated test coverage. This is especially true when I’m working on solo applications. I want the best test safety net that I can have to protect me from myself. We’re going to explore the testing packages that I commonly use on Django projects. We’ll also look at a few of the important techniques that I apply to make my testing experience great. -
Custom Response Header in Django
In this post, I'll be showing how you can add custom header to response in Django. -
Custom Response Header in Django
So I was wondering on how to build a habit of writing blogs daily, and my friend suggested that we could write about the little things we learn everyday, so we decided to start a series called Today I Learned where we will write about the little things we learn everyday, and thus build a habit I was creating this REST API for one of my clients and I was thinking what is the proof that I made this app, and I was totally blank because only proof I will have is the payment I will be receiving from the client. So I thought, what if I implant something in the response header that will scream that I have created this API or web-app or whatever. In this post, I will be documenting how we can create our own header attribute to responses in Django. Method 1 - Local Header In this you can add a custom header attribute to one response. For example, imaging you are creating an auth APi and you want to send an encrypted token as a response header. For that the view function will be something like this. def auth(req): # DO AUTH RELATED STUFF … -
Deploying and Hosting a Machine Learning Model with FastAPI and Heroku
This tutorial looks at how to deploy a machine learning model, for predicting stock prices, into production on Heroku as a RESTful API using FastAPI. -
Django News - New Django & Python Releases - Jul 3rd 2020
News Django bugfix releases issued: 3.0.8 and 2.2.14 Another bugfix release for Django 3.0 and 2.2. Django 3.1 comes out in August! djangoproject.com Python 3.7.8 and 3.6.11 released The 3.7.8 is expected to be the last bugfix release for the 3.7.x series. Future releases will focus on security fixes. blogspot.com Python Software Foundation News: 2020 Python Software Foundation Board of Directors Election Retrospective and Next Steps blogspot.com Articles Making Django App Publicly Accessible With Ngrok Ngrok is a great way to share your local Django runserver with anyone you give the link to. It makes having demo or testing webhooks locally possible. dev.to Python async frameworks - Beyond developer tribalism From Tom Christie, creator of Django REST Framework, a thoughtful overview of the async Python landscape. encode.io Store Data With Models See how to take data and store it into a database so that your application can use that data or display it later. mattlayman.com How to add a .well-known URL to your Django site A quick guide to what /.well-known/ URLs are and how to create them. adamj.eu How to find what you want in the Django documentation Many beginner programmers find the Django documentation overwhelming. mattsegal.dev Lack of … -
I'm Teaching A Live Online Django Crash Course
Course Announcement On July 16th and 17th of 2020, I'll be running a live instruction of my beginner-friendly Django Crash Course. This is a live interactive class conducted via Zoom conferencing software. We're going to walk through the book together with students. If you get stuck, there will be at least two members of the Feldroy team available to help. Each course day will have two sessions each 3 hours long, as well as an hour-long break between sessions. Attendees Receive Hours of instruction in building web apps by noted authors and senior programmers An invite to both July 16th and July 17th class days The Django Crash Course e-book (if you already bought one, we'll send you a discount code for $19.99 off the online class) Membership in our forthcoming online forums when they are activated Class Prerequisites Basic knowledge of the Python programming language Computer where you are allowed to install software (No work restrictions) Internet fast enough to join online meetings Topics Covered Setting up a development environment Cookiecutter for rapidly accelerating development Django Forms Class-Based Views Models Templates Admin Writing Django tests PyTest Factories Best practices per Two Scoops of Django Proven patterns for avoiding duplication … -
Django Login and Logout Tutorial
In this tutorial we'll learn how to configure login/logout functionality with Django's the built-in [user authentication system](https://docs.djangoproject.com/en/4.0/topics/auth/). This is the first in a three-part series that also covers [signup](https://learndjango.com/tutorials/django-signup-tutorial) and … -
Django File (and Image) Uploads Tutorial
This tutorial shows how to implement file and then image uploading with Django. We'll build a basic Instagram clone. ## Setup Whether you're on a Windows or Mac laptop the … -
Django Markdown Tutorial
[Markdown](https://daringfireball.net/projects/markdown/) is a popular text-to-HTML conversion tool for web writers. It is far easier to use than plain old HTML. Many/most static site generators provide a built-in way to write … -
Django Slug Tutorial
In this tutorial we will add slugs to a Django website. As noted in the [official docs](https://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield): "Slug is a newspaper term. A slug is a short label for something, … -
Django Best Practices: Function-Based Views vs Class-Based Views
Django's use of both function-based views (FBVs) and class-based views (CBVs) causes a lot of confusion for newcomers. Why have multiple ways to do the same thing? And which one … -
The Home Stretch - Building SaaS #63
In this episode, we return to the homeschool application that I’m building. I’m in the final stretch of changes that need to happen to make the product minimally viable. We worked on a template, wrote some model methods, and did a bunch of automated testing. We started by adding students to the context of the students index page. With the students in the context, we updated the index page to display the list of students. -
Do you need a task queue in your web app?
Within your web application, some operations, or “tasks”, take an unpredictable time to run. Others take too long to have them executed within the web application’s request/response cycle. Adding a task queue will allow you to: Run longer-running tasks outside the request-response cycle handled by web framework. Actually gunicorn or uwsgi in a production Django1 setup. Run scheduled tasks by not relying on crontab. This usually entails management commands or other forms of standalone scripts. Each needing all environment variables loaded correctly. Without a task queue Let’s say you want to send an email to a user when they submit a form. The process is shown below2: Figure 1. View sends email directly. No queue. This adds an unpredictable time to the expected response time. I.e. those 1-2 seconds taken to: talk to the email provider, over the network receive a response from the email provider, again over the network With a task queue With the task queue in place, the email sending part is done asynchronously. I.e. The unpredictable part is shifted onto the queue. And we don’t really care how long that takes; that is, for returing a response to the user. In case it fails, many task … -
Giving Django Project a “Two Scoops” Configuration
Years back I bought a physical copy of Two Scoops of Django 1.11 after seeing it highly recommended in a book called Hello Web App by Tracy Osborn.… -
Speed Up Your Django Tests - Adam Johnson
Adam Johnson personal siteSpeed Up Your Django TestsPyCon UK 2016: Cleaner unit testing with the Arrange Act Assert patternDjango Software Foundation Teamstime-machineSHAMELESS PLUGSLearnDjango - Free tutorials and premium books -
[Django Tutorial] Connect MySQL Database in Django Framework
If you are looking forward to connect your MySQL database with python code that check the following guide: In order to connect your MySQL Database in Django Framework, you should do the following: Install MySQL package Configure your settings.py Make Migrations Install MySQL Package First install MySQL via pip from your terminal with the following -
Django Static Files and Templates
Static files like CSS, JavaScript, and fonts are a core piece of any modern web application. Django provides tremendous flexibility around _how_ these files are used, however this often leads … -
Giving Django Project a “Two Scoops” Configuration
Years back I bought a physical copy of Two Scoops of Django 1.11 after seeing it highly recommended in a book called Hello Web App by Tracy Osborn. Little did I know it was way over my head at the time. With the release of Two Scoops of Django 3.X, and with a lot of recent practice, the book is now only slightly over my head, so I’ve been trying to implement more of the practices recommended in the book. I’ve also been continuing to use Docker and Docker Compose after learning the basics in Django for Professionals by Will Vincent. Fixing Problems? Early on in Two Scoops, the authors discuss how the standard project layout from django-admin startproject leaves a lot to be desired. I definitely have NOT experienced that pain because I don’t have the skills to make any complex projects. I do, however, see the value in getting comfortable with a new layout. It teaches you how some of the module inheritance in Django works. Python import statements are one of the most challenging things for me, personally, so this is a good way to train your coding skills. Let’s talk about two different project layouts. Standard … -
Huey as a minimal task queue for Django
Are you considering adding a task quee to your Django project? Then this article should be useful to you. Adding a task queue will allow you to: Run longer-running processes outside the request-response cycle handled by Django. Actually gunicorn or uwsgi in production. Run scheduled tasks by not relying on crontab. This usually entails management commands or other forms of standalone scripts. Each needing all environment variables loaded correctly. When I was “younger” task queue with Django project meant celery task queue. Now that I’m “older” there are simpler alternatives. The simplest I found was Huey. But the ideas presented here apply to evaluating all task queues for your Django project. Background Frustrated with celery and django-celery In December 2019 I was taking a Django project from Python 2 to 3. This project relied on celery and its integration for Django for asynchronous task processing. Github project link here. This work was mostly done back in 2012-2015. celery’s “Django integration” part was the first problematic part. “Problematic” in the sense that it was not being actively maintained. And Python 3 support was only “planned” at the time. Besides, by testing celery with my Python3 setup I realised how “heavy” it … -
July 16th and 17 Live Instruction of our Django Crash Course
The authors of Two Scoops of Django are offering live instruction of the Django Crash Course. This isn't a live stream, but a Zoom-powered class that isn't going to be recorded. We're going to walk-through the book together with students. If you get stuck, there will be at least two members of the Feldroy team available to help. Each course day will be seven hours long, including an hour-long break for lunch. Attendees will receive: Hours of instruction in building web apps by noted authors and senior programmers An invite to both July 16th and July 17 class days The Django Crash Course e-book (if you already bought one, we'll send you a discount code for $19.99 off the online class) Membership in our forthcoming online forums Class prerequisites: Basic knowledge of the Python programming language Computer with permissions to install software Internet fast enough to join online meetings We're selling the course for the introductory price of just $99 and space is limited, so register today!