Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Use Pathlib in Your Django Settings File
Django’s default settings file has always included a BASE_DIR pseudo-setting. I call it a “pseudo-setting” since it’s not read by Django itself. But it’s useful for configuring path-based settings, it is mentioned in the documentation, and some third party packages use it. (One that I maintain, the Scout APM Python integration, uses it.) Django has, up until now, defined it as: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) This changes in version 3.1, which as I write is still months in the future. Thanks to a contribution by Jon Dufresne and Curtis Maloney, it’s instead defined using pathlib: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parents[1] pathlib was added to Python’s standard library in Python 3.4, thanks to PEP 428. All file-path using functions across Python were then enhanced to support pathlib.Path objects (or anything with a __fspath__ method) in Python 3.6, thanks to PEP 519. pathlib is great! It has an easier API than os.path.join(), allows method chaining, and handles path normalization automatically. See how you can define a subdirectory using BASE_DIR / 'subdir'. If you want to read more, see … -
Layoffs are Coming
It’s looking increasingly likely that the COVID-19 pandemic will cause a recession. It’s easy to think we might be immune from the effects of a global recession, but my experience is that tech companies are quick to cut staff, especially engineers, in the face of declining markets. I hope I’m wrong, but I don’t think I am. Either way, it’s not going to hurt to prepare. -
Understanding many to one in Django
What is a many to one relationship? In database design many to one (or one to many) refers to a relationship between one or more entities where a single entity can have many entities connected. Let's make an example. Consider two entities: Mother and Daughter. As we know from real life, these two entities are most of the times connected like so: Every Daughter has one Mother One Mother can have many Daughters So we have a many to one here where many is the Daughter and one is the Mother. In an Entity Relationship Diagram this relationship is described with two boxes connected by the popular crow's foot: On the Mother side you can see two lines which stand for one and only one. That's the "one side" of the relationship. On the Daughter side instead you can see the crow's foot and a circle. The circle means optional, that is, there could be zero, one, or many Daughters. Technically a Mother should have at least one Daughter to qualify for her status, but I wanted to show you the circle and I took this liberty. A crow's foot with a straight line on top instead means at least … -
Django News - Issue 14 - Mar 13th 2020
News The Django Project adopts a new governance model The Django Project is switching from a core team to a Django Technical Board. Find out what this means and how the project will be governed. Django co-creator and former BDFL, Jacob Kaplan Moss, wrote Django’s new governance model to share his thoughts. djangoproject.com PyCon US 2020 has been canceled due to COVID-19 The Foundation is currently exploring options to re-schedule or cancel the conference. Any final decision to cancel or reschedule PyCon US will be made early enough to give you time to cancel or defer your travel plans. blogspot.com Python Insider: Python 3.7.7 is now available Python 3.7.7 is out! blogspot.com Articles About Removing Duplicates in the Database - DjangoTricks An elegant code snippet for removing duplicates in a database. djangotricks.com 9 Django Tips for Working with Databases Multiple tips for getting more out of Django's ORM. works-hub.com Django Best Practices - Function-Based Views vs Class-Based Views An overview of the pros/cons of each approach. learndjango.com Django's Field Choices Don't Constrain Your Data An interesting take on Field.choices in Django. adamj.eu TLDR: Generate Django Secret Key This TLDR is a quick reminder of how to generate a secret key … -
Django's new governance model
Starting today, Django has a new governance model. Previously, a small “core team” made most decisions, including electing a Technical Board to own decisions about each release. Now, the “core team” is gone; all power rests with the Technical Board. Anyone who’s made substantial contributions to Django is now eligible to run, and the board is now elected by the DSF Membership at large. You can read more about the change in today’s announcement, and if you want to full details they’re in DEP 10. -
API-First Architecture
Weekly Django Chat NewsletterDjango for APIs book Official Django REST Framework Tutorial - A Beginner's GuideAymeric Augustin 3-part series DRF Authentication Docs DjangoCon US 2018 - Finally Understand Authentication in Django REST Framework LearnDjango - The 10 Most-Used Django PackagesLearnDjango - Essential Django 3rd Party Packages -
How to serve private media files with Django
In this tutorial, we will create a barebones document manager with these features: Logged in users can upload files. Superusers can view all files. Regular users can view only the files they uploaded. These steps were performed on Ubuntu 18.04 LTS. Getting Started First lets add the universe repository and install python3-venv. sudo add-apt-repository universe sudo apt install -y python3-venv The Project and App Now create the project. mkdir ~/.virtualenvs python3 -m venv ~/... -
Website Search using Django and PostgreSQL Trigrams
Over the years I've become increasingly wary of the word "easy" in software documentation. Pick a software project at random, and there's a good chance that “easy” will appear early on. Over the years I've become increasingly wary of the word "easy" in software documentation. Pick a software project at random, and there's a good chance the documentation will lead off with something like "Booloogent makes the process of frobnifying your wakalixes easy!" And then you try to use the package or feature or whatever, and you find that it is not easy. It might not work at all, and you might grow angry with the author of Booloogent for lying, or with yourself for failing at something so easy, or maybe both at once. So it's refreshing - even exhilarating - when a thing really does turn out to be easy. And such is the case with Django's "trigram_similar" lookup. One of Imaginary Landscape’s healthcare clients needed a search function (in their Django-based website) that would allow users to find medical service facilities by entering either the provider's name or some component of their address, such as a street name or a city. The search widget also had to … -
Using Django Check Constraints for the Sum of Percentage Fields
I previously covered using Django’s CheckConstraint class to ensure a field with choices is constrained to only valid values. Here’s another use case, based on an application I worked on. It uses a check constraint to ensure a set of fields, representing percentages, always sum up to 100. Imagine a book application where we want to track books our percentage progress in three categories: Pages we’ve read Pages we have left to read Pages we have deliberately chosen to ignore We could use a Django model with one field for each of those three categories: from django.db import models class Book(models.Model): percent_read = models.PositiveIntegerField() percent_unread = models.PositiveIntegerField() percent_ignored = models.PositiveIntegerField() def __str__(self): return f"{self.id} - {self.percent_read}% read" Using PositiveIntegerField means no field contains a number less than 0. That’s a good start, but the fields can still store numbers greater than 100, or their sum might be less or more than 100. Using a check constraint, we can enforce such constraints, telling the database to prevent storage of bad data. In this case, we only need to enforce that their sum is 100 to automatically bound the individual fields between 0 and 100. We add such a constraint in the … -
QuerySets of various models
In general, the first thing we try to do to reduce the load time of a page in Django is to reduce the number of queries we are making to the database. This often has the greatest impact, sometimes orders of magnitude greater than other improvements. One problem I recently hit with a specific set of pages was that there are potentially seven different models that may have zero or more items for a given request. This could mean we do seven queries that are all empty. These are for all distinct models, but in this case, they are used for the same purpose, and this case, we always need all of them, if there are any relevant records. Whilst there are seven models, there may be more in the future. Each of these models has a specific method, that validates some data against the rules that are applicable to that model, and the stored attributes. But each model has a different set of attributes, and future models will more than likely have different attributes. There are at least three different ways we could have solved this problem. It turns out we have solved similar problems in the past the … -
The Simplest Way to Create a Python Virtual Environment
A lot of fog and mysteries surround Python virtual environments. There are loads of packages, tools, and wrappers trying to make developer's life with virtual environments easier. But if we look at the basics, we'll see that actually, creating a virtual environment in Python has never been easier. Starting from … Read now -
Python in GitHub Actions
GitHub’s own CI called GitHub Actions has been out of closed beta for a while and offers generous free quotas and a seamless integration with the rest of the site. Let’s have a look on how to use it for an open source Python package. -
Django News - Issue 13 - Mar 6th 2020
News Django security releases issued for 3.0.4, 2.2.11, and 1.11.29 A new security and bug fix release. As ever, updating to the latest version is always recommended. PSA: This is very likely to be the last release of Django 1.11. Time to move on if you're still there. (via Carlton Gibson) Django 1.11 LTS reaches the end of extended support in April 2020. djangoproject.com 30% off PyCharm with all proceeds towards Django Receive 30% off the powerful PyCharm editor. All proceeds benefit the Django Software Foundation. jetbrains.com Articles The Django Speed Handbook: Making a Django app faster This comprehensive handbook has something for everyone from the backend to even some helpful frontend tricks. openfolder.sh How to Disallow Auto-named Django Migrations Adam Johnson walks us through three methods for disallowing Django's auto-named Migrations, which includes Django's check system and pre-commit hooks, which may be new to you. adamj.eu Views on Views Matt Layman explains one of Django's core building blocks, Django Views. mattlayman.com Mental Models for Class Based Views This article is a deep dive into how Django's class-based views work behind the scenes. djangodeconstructed.com Sponsored Link Django Crash Course: Covers Python 3.8 and Django 3.x - Alpha Version The authors … -
Views On Django
Full show notes are available at https://www.mattlayman.com/django-riffs/3. -
Episode 3 - Views On Django
On this episode, we look at views, a major component within Django and a primary place where your code will run. Listen at djangoriffs.com. Last Episode On the previous episode, we talked about URLs and how they describe the main interface that a browser can use to interact with your application. What Is A View? A view is a chunk of code that receives an HTTP request and returns an HTTP response. -
Rotterdam python meetup
Microservices with Python for AI in radiology - Coert Metz In radiology, people take a long time to become experienced. Medical school, MD, certified radiologist... And when they're 68 they're off to a pension. What they did at Quantib was to try and "scale radiology experience with AI". Detection and classification of prostate lesions. Same with breast MRIs. Brain shrinkage. They hope it increases the amount of MRI scans that can be processed. And also the quality of the analysis. He demoed the application. There's detection of brain regions in the software, for instance. When you compare two MRI scans at different points in time, you can see the difference and compare that difference with what you would see in a healthy person. Hospital practice often means downloading radiology RMI images from a central hospital image storage server ("PACS"), taking them to a separate workstation for analysis and then going back with reports. This takes time, so it is sometimes omitted due to time pressure... What they're working on now is to run their AI software on a server and connect it to the image storage service. They designed their software as a bunch of microservices. Storage service, import, dispatch, … -
Resources & Mentorship
Weekly Django Chat NewsletterDjango ForumDjango Conference Videosdjango-users Google groupDjango RSS feedsDjango News newsletterdjangopackages.orgdjangosnippets.org -
How To Style Sign Up - Building SaaS #47
In this episode, I added styling to the Sign Up page of the site. We chatted about CSS tools and frameworks, the benefit of feature flags to control what UI is displayed to users, and how to use Tailwind CSS to modify a design quickly. In the first portion of the stream, we focused on CSS frameworks. We compared Bootstrap, Semantic UI, and Tailwind CSS. After that discussion, I talked about feature flags. -
Postgres VIEW from Django QuerySet
It's [already possible](https://schinckel.net/2014/09/01/postgres-view-meet-django-model/), given an existing Postgres (or other database) VIEW, to stick a Django Model in front of it, and have it fetch data from that instead of a table. Creating the views can currently be done using raw SQL (and a RunSQL migration operation), or using [some helpers](https://schinckel.net/2017/06/07/versioning-complex-database-migrations/) to store the SQL in files for easy versioning. It would be excellent if it was possible to use Django's ORM to actually generate the VIEW, and even better if you could make the migration autodetector generate migrations. But why would this be necessary? Surely, if you were able to create a QuerySet instance that contains the items in your view, that should be good enough? Not quite, because currently using the ORM it is not possible to perform the following type of query: {% highlight sql %} SELECT foo.a, foo.b, bar.d FROM foo INNER JOIN ( SELECT baz.a, ARRAY_AGG(baz.c) AS d FROM baz GROUP BY baz.a) bar ON (foo.a = bar.a) {% endhighlight %} That is, generating a join to a subquery is not possible in the ORM. In this case, you could probably get away with a correlated Subquery, however that would probably not perform as well as … -
How to Make Django Redirect WWW to Your Bare Domain
If you’re hosting a website on a top level domain, you should set up both the bare domain (example.com) and the “www” subdomain (www.example.com). People expect to be able to type either version and see your site - no matter which version you advertise. The fashion these days seems to be to use the bare domain - as argued by dropwww.com. That said, some say we still need the “www” - as argued by www.yes-www.org. Personally, I side with the bare domain crowd. I don’t think any of the technical arguments either way are showstoppers, and it’s nicer to type less. But anyway, whichever side you’re on, you’ll want to redirect from one to the other. If you don’t, some users won’t find your site. In this tutorial we’ll set up a www -> bare domain redirect. If you want the opposite, you should be able to follow along and just swap the positions. Where to Redirect? You can configure such a redirect at one of several layers in your stack. DNS Provider Some DNS providers provide a “redirect” DNS record. This isn’t a real DNS record. Instead, it points the domain at their web servers, which then serve HTTP … -
Django News - Tips on testing, templates, and Django within healthcare. - Feb 28th 2020
News Python Insider: Python 3.8.2 and 3.9.0a4 are now available Python 3.8.2 contains numerous new bug fixes while 3.9.0a4 is the fourth of six planned alpha releases leading up to its planned release in August. blogspot.com Sponsor Django on Github Django relies on community donations and now you can fund it directly via Github. Currently 40+ monthly sponsors. github.com Articles Django Best Practices - Template Structure A look at the two dominant ways to structure templates in a Django app. learndjango.com The Ultimate Guide to Django Redirects – Real Python An in-depth look at HTTP redirects and multiple ways to implement them in Django. realpython.com Automating Performance Testing in Django A guide to spotting N+1 query issues in your Django app. testdriven.io Sponsored Link Django Crash Course: Covers Python 3.8 and Django 3.x - Alpha Version The authors of Two Scoops of Django have released their latest book, the Django Crash Course. Based on their corporate training, they are offering the book for under US$20, which is a steal considering they normally charge $3000/person for in-person training. This book, currently 50 chapters long, is intended for passionate learners willing to get the latest, most cutting-edge written materials. Now in beta, … -
Adding Metadata to PDFs
For both Django Crash Course and the forthcoming Two Scoops of Django 3.x, we're using a new process to render the PDFs. Unfortunately, until just a few days ago that process didn't include the cover. Instead, covers were inserted manually using Adobe Acrobat. While that manual process worked, it came with predictable consequences. Merging the PDFs This part was easy and found in any number of blog articles and Stack Overflow answers. Step 1: Install pypdf2 Step 2: Write a script as seen below from PyPDF2 import PdfFileMerger now = datetime.now() pdfs = [ 'images/Django_Crash_Course_5.5x8in.pdf', '_output/dcc.pdf', ] merger = PdfFileMerger() for pdf in pdfs: merger.append(pdf) merger.write("releases/beta-20200226.pdf") merger.close() It was at this point that we discovered that our new file, releases/beta-20200226.pdf, was missing most of the metadata. Oh no! Adding the Metadata According to the PyPDF2 docs, adding metadata is very straight-forward. Just pass a dict into the addMetadata() function. I inserted this code right before the call to merger.write(): merger.addMetadata({ "Title": "Django Crash Course", "Authors": 'Daniel Roy Greenfeld, Audrey Roy Greenfeld', "Description": "Covers Python 3.8 and Django 3.x", "ContentCreator": "Two Scoops Press", "CreateDate": "2020-02-26", "ModifyDate": "2020-02-26", }) The PDF built! Yeah! Time to open it up and see the results! … -
Advanced usage of Python requests - timeouts, retries, hooks
The Python HTTP library [requests](https://requests.readthedocs.io/en/master/) is probably my favourite HTTP utility in all the languages I program in. It's simple, intuitive and ubiquitous in the Python community. Most of the programs that interface with HTTP use either requests or urllib3 from the standard library. While it's easy to immediately be productive with requests because of the simple API, the library also offers extensibility for advanced use cases. If you're writing an API-heavy client or a web scraper you'll probably need tolerance for network failures, helpful debugging traces and syntactic sugar. Below is a summary of features I've found useful in requests when writing web scraping tools or programs that extensively use JSON API's. [TOC] ## Request hooks Often when using a third party API you want to verify that the returned response is indeed valid. Requests offers the shorthand helper `raise_for_status()` which asserts that the response HTTP status code is not a 4xx or a 5xx, i.e that the request didn't result in a client or a server error. For example ```python response = requests.get('https://api.github.com/user/repos?page=1') # Assert that there were no errors response.raise_for_status() ``` This can get repetitive if you need to `raise_for_status()` for each call. Luckily the requests library … -
Django & Healthcare - Jacinda Shelly
Weekly DjangoChat NewsletterDoctor on DemandApero HealthDjangoCon US 2014 - Connecting Patients to Doctors in Real-Time Using DjangoPyCon 2019 - But, Why is the (Django) Admin Slow?PyCon 2019 - Hands-On Web Application Security with DjangoDjango Forum - Top 5 3rd party packagesqrDjangoCon 2017 - Programming Post-Progeny -
A Week At A Time - Building SaaS #46
In this episode, we worked on a weekly view for the Django app. We made navigation that would let users click from one week to the next, then fixed up the view to pull time from that particular week. The first thing that I did was focus on the UI required to navigate to a new weekly view in the app. We mocked out the UI and talked briefly about the flexbox layout that is available to modern browsers.