Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
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. -
Dockerizing Flask with Postgres, Gunicorn, and Nginx
This tutorial details how to configure Flask to run on Docker along with Postgres, Nginx, and Gunicorn. -
How to Disallow Auto-named Django Migrations
When you run Django’s manage.py makemigrations, it will try to generate a name for the migration based upon its contents. For example, if you are adding a single field, it will call the migration 0002_mymodel_myfield.py. However when your migration contains more than one step, it instead uses a simple ‘auto’ name with the current date + time, e.g. 0002_auto_20200113_1837.py. Naming things is a known hard problem in programming. Having migrations with these automatic names makes managing them harder. In the worst case, their similarity could lead to data loss when trying to roll back in an emergency. It’s also all too easy to forget to fix the name and commit since Django doesn’t prompt you for a better name. We can guard against this with some automation! The below custom system check will ensure you don’t commit such migrations to your project. I’ve replicated in a couple projects so figure it’s worth sharing the code, but it’s a bit small to publish as a package. Let’s look at adding it, as per the guide on custom system checks. To add it your project, you’ll first want to add it to a module inside one of your apps. I normally write … -
Python in Production
I’m missing a key part from the public Python discourse and I would like to help to change that. -
Django News - Issue 11 - Feb 21st 2020
News Wagtail 2.8 is released! In case you missed it, Wagtail 2.8 was released and adds Django 3.0 support while dropping Django 2.0 support plus a bunch of new features and bugfixes. github.com 🚨 Docker/Postgres now requires a username & password In the latest version of Docker, Postgres now requires either a username & password to be set, or use another setting to allow non-pw access. This affects all Postgres versions for Docker. This is better for security, but frustrating that Docker made such a major change in this quiet way. It breaks many existing builds. github.com Articles How to cheat at unit tests with pytest and Black From Django co-creator Simon Willison, a clever way to combine pytest with the Black Python formatter. simonwillison.net A Tip About DRF Permissions Use permission classes and operators to simplify your Django REST Framework permissions. revsys.com Automating Performance Testing in Django A guide to testing--and avoiding--N+1 queries. testdriven.io How to add a robots.txt file to your Django site Add a testable robots.txt file to your Django site. adamj.eu Alpine makes Python Docker builds 50× slower, and images 2× larger Do you work with Docker? An interesting article on the alpine build many of … -
Templates and Logic - Building SaaS #45
In this episode, we added content to a template and talked about the N+1 query bug. I also worked tricky logic involving date handling. The first change was to update a course page to include a new icon for any course task that should be graded. After adding this, we hit an N+1 query bug, which is a performance bug that happens when code queries a database in a loop. We talked about why this happens and how to fix it. -
Getting data to home page with Django
In this post I show how to use get_context_data(). You might need it to display 'latest posts' on your 'home page'. -
Thanks, Lukas! This is a really helpful article!
Thanks, Lukas!This is a really helpful article! -
Django Software Foundation
Weekly DjangoChat NewsletterDjango Software FoundationSponsorship & GitHub SponsorsHow Django Works Behind the ScenesDjango MerchandiseDSF Individual Membersdjangosnippets.orgjazzbandDjango PeopleDjango Forum -
The Innovation/Execution Spectrum
Lately I’ve been working with our startups to establish their engineering strategies. One model I’ve found useful is to place their technical challenge on an innovation/execution spectrum. -
Views On Views
In the previous Understand Django article, I covered URLs and the variety of tools that Django gives us to describe the outside interface to the internet for your project. In this article, we’ll examine the core building block that makes those URLs work: the Django view. What Is A View? A view is a chunk of code that receives an HTTP request and returns an HTTP response. Views describe Django’s entire purpose: to respond to requests made to an application on the internet. -
Safely Including Data for JavaScript in a Django Template
Django templates are often used to pass data to JavaScript code. Unfortunately, if implemented incorrectly, this opens up the possibility of HTML injection, and thus XSS (Cross-Site Scripting) attacks. This is one of the most common security problems I’ve encountered on Django projects. In fact I’ve probably seen it on every considerably-sized Django project, in some form or another. Also, not naming and shaming, but I’ve also seen it in lots of community resources. This includes conference talks, blog posts, and Stack Overflow answers. It’s hard to get right! It’s also been historically difficult, since it’s only Django 2.1 that added the json_script template tag to do this securely. (And the ticket was open six years!) Let’s look the problem and how we can fix it with json_script. The Vulnerable Way Let’s take this view: from django.shortcuts import render def index(request): mydata = get_mydata() return render(request, 'index.html', context={"mydata": mydata}) …and this template: <script> const mydata = "{{ mydata|safe }}"; </script> Unfortunately as written, the template is open to HTML injection. This is because if the data contains </script> anywhere, the rest of the result will be parsed as extra HTML. We call this HTML injection, and attackers can use it … -
How to search in a huge table on Django admin
Hello everyone! We all know that the Django admin is a super cool tool for Django. You can check your models, and add/edit/delete records from the tables. If you are familiar with Django, I’m sure you already know about it. I was given a task: Our client wanted to search in a table by one field. It seems easy enough, right? Well, the tricky part is that the table has 523.803.417 records. Wow. 523.803.417 records. At least the model was not that complex: On models.py: class HugeTable(models.Model): """Huge table information""" search_field = models.CharField(max_length=10, db_index=True, unique=True) is_valid = models.BooleanField(default=True) def __str__(self): return self.search_field So for Django admin, it should be a breeze, right? WRONG. The process First, I just added the search field on the admin.py: On admin.py: class HugeTableAdmin(admin.ModelAdmin): search_fields = ('search_field', ) admin.site.register(HugeTable, HugeTableAdmin) And it worked! I had a functioning search field on my admin. Only one problem: It took 3mins+ to load the page and 5mins+ to search. But at least it was working, right? WTF? First, let’s split the issues: Why was it taking +3mins just to load the page? Why was it taking +5mins to search if the search field was indexed? I started tackling …