Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Using Comments in JSON with Node.js and JavaScript Examples
In this article, we'll learn how to use comments in JSON files. We'll see workarounds and methods used by developers to add single-line and multiple-line comments to their JSON files, the external libraries and packages for stripping comments from your files before feeding them to the regular JSON.parse() method in JavaScript and Node.js and we'll also see simple JavaScript code for removing comments without external libraries. Finally, we'll see the alternative formats to JSON that support comments such as JSON5 and JSONC. JSON Doesn't Support Comments! As you might be aware of, JSON doesn't support comments! But as programmers, we are used to add comments so in this article, we'll see the possible ways that we have to use comments in our JSON files even if they are natively supported by the format. In fact, comments were not always missing in JSON but were removed later. This is the reason of removing comments from JSON as stated by Douglas Crockford. I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. JSON can be mostly needed if you use JSON for your configuration files even if JSON in … -
Removing Comments from JSON with Python
JSON doesn't permit comments by design. As explained by its creator Douglas Crockford. I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. But he also stated that you can use external or built-in tools to pre-parse JSON files and remove any comments before the actual parsing takes place. In this short article, we'll see how you can remove comments from JSON files using Python code. How to Read JSON Files with Python First, we need to be able to read JSON files in our Python code: import json with open('example.json') as json_file: data = json.load(json_file) print(data) How to Remove Comments from your JSON File There are various workarounds used by developers to add comments to JSON files generally. You can use JS-style comments (single-line // and multiline /* .. */) in your JSON files and pre-parse them with your Python code to remove the comments before reading them in the previous way: import json with open('data.json', 'r') as jsonfile: jsondata = ''.join(line for line in jsonfile if not line.startswith('//')) data = json.loads(jsondata) print(data) You can also use external packages such as: JSON-minify: A port of the … -
What happens when you run manage.py test?
This is a blog post version of the talk I gave at DjangoCon Australia 2020 today. There’s also the slides repository which contains the full example code. You run your tests with manage.py test. You know what happens inside your tests, since you write them. But how does the test runner work to execute them, and put the dots, E’s, and F’s on your screen? When you learn how Django middleware works, you unlock a huge number of use cases, such as changing cookies, setting global headers, and logging requests. Similarly, learning how your tests run will help you customize the process, for example loading tests in a different order, configuring test settings without a separate file, or blocking outgoing HTTP requests. In this post, we’ll make a vital customization of our test run’s output - we’ll swap the “dots and letters” default style to use emojis to represent test success, failure, etc: $ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). 💥❎❌⏭✅✅✅✳️ ... ---------------------------------------------------------------------- Ran 8 tests in 0.003s FAILED (failures=1, errors=1, skipped=1, expected failures=1, unexpected successes=1) Destroying test database for alias 'default'... But before we can write that, we need … -
Django Hosting & Deployment Options
[Django](https://www.djangoproject.com/) websites can be deployed on any number of hosting providers. The first choice is deciding whether to use a Platform-as-a-service (PaaS) option or a virtual private server (VPS). A … -
Django News - Django Security Release! - Sep 4th 2020
News Django security releases issued: 3.1.1, 3.0.10 and 2.2.16 Time to update your Django version! djangoproject.com Events Django Day 2020 - Sept 25th Djangonauts from in and around Denmark are meeting up for the second edition of Django Day, to be held on September 25th 2020. It will be a full day of talks, either to be experienced online -or- at our venue with safe social distancing. djangoday.dk Articles Django ORM if you already know SQL An illustrated guide to Django's ORM by drawing analogies to equivalent SQL statements. dev.to OneToOne Relationship Linking your user model to your custom profile model in Django. hashnode.dev Bonus Django Documentation Sites Links and brief descriptions of Classy Class-Based View/Forms/REST Framework which are vital additional documentation resources. adamj.eu Demystifying Django’s Magic Precious Ndubueze breaks down a default Django project one generated file and folder at a time. smashingmagazine.com Linux Commands for Developers A good introduction to basic Linux commands for developers. This is a nice refresher for developers of any skill level. dev.to Podcasts Running in Production - DataWellness DataWellness is a Django service that helps organizations stay safe and compliant, hosted on a single DigitalOcean server and up since 2016. runninginproduction.com Test & … -
Custom Form Validation - Building SaaS #71
In this episode, I added some custom checking to ensure that students may only be enrolled in a single grade level for a school year. We talked about form cleaning and wrote a for unit test to prove that the change worked. After that change, we switched to a template and wrote copy for when no progress reports are viewable for users. With the first issue, I needed to update a form that enrolls students. -
Bonus Django Documentation Sites
There are a few mini sites out there with “bonus” Django documentation. Here’s a list of the best ones I know of. Classy Class-Based Views Classy Class-Based Views is a class explorer for the class-based view (CBV) hierarchy in Django: If you’re struggling to figure out what’s going on in your CBV’s, this is a real boon for navigating them. It was created by Charles Denton and Marc Tamlyn. It seems to be a little unmaintained at current, but the information within should still be fairly accurate since Django’s CBV’s don’t change often. Whilst on the topic of CBV’s, I can’t help but mention django-vanilla-views: This is a library that provides a simpler CBV hierarchy, with a comparison against Django’s built-in one. It was created by Tom Christie and I help maintain it. Classy Django Forms Classy Django Forms is a similar class explorer for Django’s forms and form fields: It’s a project by Ana Balica, based on Classy Class-Based Views, and seems to be up to date with Django 3.0 at least. Template Tags and Filters Template Tags and Filters is a cheatsheet for Django’s template language: It was made this year so should be up to date with … -
Office Hours
Ask me professional questions in a small group Zoom meeting setting. Past topics of discussion have included: Code review! Attendees can share code with me, unless given permission I won't share with other attendees even though I will comment verbally on it. Project design and architecture Resolving bugs in code Career advice Managing tough job situations Resume and portfolio evaluation Next session is 10AM to Noon PST / 5PM-7PM UTC on Wednesday, September 2nd, 2020. Sign up now! -
Django Testing Tutorial
Testing is an important but often neglected part of any Django project. In this tutorial we'll review testing best practices and example code that can be applied to any Django … -
Authenticating Django PostgreSQL User in Multiple Docker Compose Environments
I’ve been building a Django project template using Docker Compose, PostgreSQL, and Nginx. Docker is a definite weak point for me, so I used an article from Michael Herman to set it up: Dockerizing Django with Postgres, Gunicorn, and Nginx. I made some additions to that tutorial – custom user model, re-organized config files – but I kept running into the same issue… Django Can’t Connect to Postgres When switching between development and production environments, Django could not connect to my postgres database: docker-compose up -d --build docker-compose exec web python manage.py migrate django.db.utils.OperationalError: FATAL: password authentication failed for user "" I had set up the same username for both the development and the production environment postgres services, but the passwords were different. For some reason, Docker Compose wasn’t re-configuring postgres with the new information when I switched containers. Temporary Fix I was able to avoid the problem with some help from the testdriven.io tutorial mentioned above: docker-compose down -v docker-compose -f docker-compose.prod.yml down -v The -v flag brings down all volumes, i.e. my postgres database. Then, when bringing the containers back up, Docker Compose would say, “I don’t have any volume called postgres_data. I better make one!” This would … -
Django and the N+1 Queries Problem
This is a cross-post from the Scout APM blog, where I occasionally write. I also maintain the Scout Python integration. The N+1 Queries Problem is a perennial database performance issue. It affects many ORM’s and custom SQL code, and Django’s ORM is not immune either. In this post, we’ll examine what the N+1 Queries Problem looks like in Django, some tools for fixing it, and most importantly some tools for detecting it. Naturally Scout is one of those tools, with its built-in N+1 Insights tool. We’ll cover: What Is the N+1 Queries Problem? N+1 Queries 2N+1 Queries NM+N+1 Queries Tools to Fix the N+1 Queries Problem select_related() prefetch_related() django-auto-prefetch Tools for Finding N+1 Query Problems django-debug-toolbar nplusone Scout APM What Is the N+1 Queries Problem? In a nutshell: code that loops over a list of results from one query, and then performs another query per result. Let’s look at a basic example and a couple of its natural extensions. N+1 Queries Say we had this code: books = Book.objects.order_by("title") for book in books: print(book.title, "by", book.author.name) This code uses print() for simplicity, but the problem exists in all other ways data might be accessed, such as in templates or views … -
Introducing Tight.ai - My First Desktop App
I just released a production-g... -
Django Best Practices: Referencing the User Model
Django has a powerful, built-in [user authentication system](https://docs.djangoproject.com/en/4.0/topics/auth/default/) that makes it quick and easy to add [login, logout, and signup functionality](https://learndjango.com/tutorials/django-login-and-logout-tutorial) to a website. But how should a Django developer … -
Flask Stripe Tutorial
This tutorial looks at how to quickly add Stripe to a Flask app in order to accept payments. -
Django News - Django Technical Board Election - Aug 28th 2020
News Announcement of Technical Board Election Registration There is an upcoming Django Technical Board election. All current DSF Members are automatically registered for this election. If you are not a DSF Member but would like to vote in this election there is a form to fill out. djangoproject.com Black 20.8b1 Pre-release of the latest version of Black, the opinionated Python formatter. github.com Wagtail 2.10.1 release notes Bugfix release for the lastest major Wagtail version. wagtail.io GitHub Changelog: Set the default branch for newly-created repositories GitHub now allows you to change your default branch name for newly-created repositories. PSA: On October 1, 2020, GitHub is changing the default from master to main. github.blog Events PyCon AU / DjangoCon AU 2020 - Sept. 4th – 6th, 2020 PyConline AU and DjangoCon AU are one week away! pycon.org.au Articles Administer All the Things The next in a series by Matt Layman, this in-depth tutorial focuses on the Django admin. mattlayman.com Python Tools for Managing Virtual Environments A comprehensive look at the multiple ways to manage Python virtual environments. dev.to Test Elasticsearch in Django Without Mocking Use Django and pytest to test Elasticsearch without mocking. yanglinzhao.com Tutorials Deploying a Production-ready Django app on AWS … -
Authenticating Google Client Library for a Django Application
Recently I was tasked with integrating Google Sheets with Django. It was necessary for a row to be added to a Google Sheet on completion of a user action. Having no experience with interacting with Google Sheets programmatically, a quick search found me the Google Sheets API V4 Python Quickstart Guide. Remember: I needed to append a row a Google sheet on behalf of the application NOT the user. OAuth I followed the quickstart guide and was able to create a functioning application that was able to add a row to Google Sheets. However as I simply followed the Quickstart guide I only experienced the OAuth workflow. This meant I was required to sign in, in order to get my application to make changed to the Google Sheet. This was not viable in a production environment. OAuth would only make sense if I was manipulating Google Sheets on a users behalf. It would be ok for a user to be shown a Google login page to complete and on completion their access token to be stored on the server for authentication to the API. I haven’t provided any code examples for this because Google have already provided this here. API … -
Authenticating Google Client Library for a Django Application
Recently I was tasked with integrating Google Sheets with Django. It was necessary for a row to be added to a Google Sheet on completion of a user action. Having no experience with interacting with Google Sheets programmatically, a quick search found me the Google Sheets API V4 Python Quickstart Guide. Remember: I needed to append a row a Google sheet on behalf of the application NOT the user. OAuth I followed the quickstart guide and was able to create a functioning application that was able to add a row to Google Sheets. However as I simply followed the Quickstart guide I only experienced the OAuth workflow. This meant I was required to sign in, in order to get my application to make changed to the Google Sheet. This was not viable in a production environment. OAuth would only make sense if I was manipulating Google Sheets on a users behalf. It would be ok for a user to be shown a Google login page to complete and on completion their access token to be stored on the server for authentication to the API. I haven’t provided any code examples for this because Google have already provided this here. API … -
Predicting The Future - Building SaaS #70
In this episode, we worked on two issues. The first issue was fixing incorrect projected completion dates of tasks. We used test driven development to reveal the bug and work on the fix. The second issue add some extra data to display on a page. We picked a couple of tasks at random to fix for this stream session. The first issue related to the course view when paired with what the student’s actions. -
Python Dependency Injection
This post looks at how to use dependency injection to decouple and improve the design of a Python application. -
Mirrors migrated out of bitbucket
As you are probably aware, bitbucket is dead. At least the original bitbucket as we knew it, the leader in mercurial hosting. They no longer host mercurial repositories, so I had to move my kernel and Django mirrors. They are now hosted on my own heptapod instance, at the following URL: https://hg.freehackers.org/ I did the […] -
Administer All The Things
In the previous Understand Django article, we used models to see how Django stores data in a relational database. We covered all the tools to bring your data to life in your application. In this article, we will focus on the built-in tools that Django provides to help us manage that data. What Is The Django Admin? When you run an application, you’ll find data that needs special attention. Maybe you’re creating a blog and need to create and edit tags or categories. -
How to configure Environment Specific settings in Python Django Framework?
There are certain configurations in your settings.py such as DEBUG, STATIC_URL, DATABASES, SECRET_KEY, ALLOWED_HOSTS, etc. These settings are actually the ones that you need to look after while deploying to the production environment. Whenever your application goes live, you shouldn't display your debug logs, or error messages on the browsers. This will make your application vulnerable. Also you might want to put different secret keys. For these reasons, we need environment-specific settings. In this tutorial, I will be creating different settings for local, development, and production environment. -
Django News - Issue 37 - Aug 21st 2020
News GSOD 2020 Project - Django Internals / Mentorship With Google Season of Docs (GSOD) kicking off, Gabby Precious wants to know if you have any specific challenges with Django's contribution documentation? djangoproject.com Python Insider: Python 3.7.9 and 3.6.12 security updates now available The lastest security fix rollups for Python 3.7 and Python 3.6 are now available. blogspot.com Tailwind CSS v1.7.0 (1.7.1, 1.7.2, and 1.7.3) The Tailwind CSS v1.7.x release adds a bunch of new features ranging from gradients, background-clip, gap, contents display, font-size letter-spacing, and more interesting new features. tailwindcss.com Events DjangoCon Australia 2020: Schedule live and tickets on sale 🎟️ Tickets are on sale and the schedule has been released for the 8th DjangoCon AU. djangoproject.com Articles Running Django Tests in Github Actions A nice, concise introduction to how to use GitHub Actions as a CI platform for testing your Django code. banagale.com A deep dive into the official Docker image for Python Itamar Turner-Trauring Itamar does an excellent job of deconstructing the official Python image for Docker and gives some sound advice and tips along the way. pythonspeed.com Why Internationalization and Localization matters by Nicolle Cysneiros A practical and concise guide to Internationalization and Localization using Python … -
Create icns Icons for macOS Apps.
I've been working a lot with E... -
We've released a new python book!
That's right, we've released Practical Python Projects, a book of twelve bite-sized weekend projects to enhance your Python knowledge! And the first 25 people to use code "ppp-feldroy-blog" will get 15% off the purchase price! Practical Python Projects is a book authored by Yasoob Khalid. We've admired Yasoob's code and writing for years. The level of his work is set at the level of quality the Feldroy team constantly strive to meet. In fact, you can read for free Yasoob's popular and free first book, Intermediate Python. This book does more than just walk readers through code, it teaches how the research was done for each project. Building off this research, each chapter ends with a "next steps" section guiding the reader towards making the project unique to themselves. Want to know what we think of Practical Python Projects? "A favorite way to for developers to grow their programming skills is by building small practical projects. Yasoob's book embraces this idea, taking the reader on a tour of over a dozen projects, reinforcing research and coding skills along the way. His technical acumen combines with unbridled enthusiasm to make for a delightful and informative book." -- Daniel Feldroy, co-author of …