Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Building User Interfaces
Full show notes are available at https://www.mattlayman.com/django-riffs/4. -
Onboarding Forms - Building SaaS #51
In this episode, we added the first form to collect data in the onboarding flow. We used a CreateView and defined all the fields that are needed in the HTML form. I started by filling in the HTML form structure of the page. Once the dummy version was in place, we changed from a TemplateView to a CreateView and began fixing each configuration error that the new view type reported as missing like missing a model field declaration. -
Translations - Andrew Knight
Weekly Django Chat NewsletterAutomationPanda.com@automationpandaEast Meets West When Translating Django Apps article and video (21:20 - 45:40)PyCarolinasdjango-news.comDjango i18N Google Group -
Speeding up a Django web site without touching the code
I’ve recently been tweaking my server setup for a Django 1.3 web site with the goal of making it a bit faster. Of course, there is a lot of speed to gain by improving e.g. the number of database queries needed to render a web page, but the server setup also has an effect on the web site performance. This is a log of my findings. All measurements have been done using the ab tool from Apache using the arguments -n 200 -c 20, which means that each case have been tested with 20 concurrent requests up to 200 requests in total. The tests was run from another machine than the web server, with around 45ms RTT to the server. This is not a scientific measurement, but good enough to let me quickly test my assumptions on what increases or decreases performance. The Django app isn’t particularly optimized in itself, so I don’t care much about the low number of requests per second (req/s) that it manages to process. The main point here is the relative improvement with each change to the server setup. The baseline setup is a Linode 1024 VPS (Referral link: I get USD 20 off my … -
Comics v2.2.0 released with Django 1.5 support
Version 2.2.0 of my comics aggregator is now released. It features a general upgrade of dependencies, including the move from Django 1.4 to Django 1.5, and a lot of updates to comic crawlers. The Django upgrade was completed months ago and it’s been running my Comics instance since, so it’s about time to get it released before Django 1.6 arrives in a month or two. Regarding the crawler updates, it’s a bit sad to see that many of the crawlers have been broken for months without me or anybody else noticing, but it’s hard to catch some content lacking in the middle of a firehose of similar content. I guess I’ll have to make it a monthly task to look through the crawler status page of my Comics instance and do patch releases with updated crawlers. Check out the project docs for more information about Comics and this release in particular. -
Comics v2.3.0 released with better mobile support
Version 2.3.0 of my comics aggregator is now released. As always, dependencies have been updated, including the routine Django upgrade from Django 1.5 to 1.6, just in time for the upcoming 1.7 release. The largest change this time around is the move from Bootstrap 2 to 3, which includes a refreshed, flatter design and lots of tweaking to make Comics both look good and work nicely on mobile devices, something it didn’t use to do. The dependency overview at requires.io has been a great motivation for doing some maintenance work on Comics. The only dependency left outdated is django-registration, as 1.0 moves to class-based views, which requires some larger changes to my customizations. Thus, the upgrade of django-registration has been deferred together with the related upgrade of my vendorized copy of django-invitation. Most, if not all, of the other dependencies seems to support Python 3 now, though some lack the right Trove classifiers in their PyPI registration, so they are not correctly labeled by requires.io. I found an open pull request for cssmin and a recent commit for django-compressor adding the missing Trove classifiers. I’ve also done my part to improve the Python 3 metadata by sending a pull request … -
Episode 4 - Building User Interfaces
On this episode, we look at templates, the primary tool that Django provides to build user interfaces in your Django app. Listen at djangoriffs.com. Last Episode On the previous episode, we talked about views and how views handle requests to create HTTP responses for users. Set Up Templates are static files that Django will fill in with data. In order to use those files, we must instruct Django on where to find them. -
Django Security Headers Hall of Fame
It’s been a year since I published How to Score A+ for Security Headers on Your Django Website, the blog post for my DjangoCon Europe 2019 talk. It’s seen some updates as both Django and web security have evolved, for example Feature-Policy is now required for an A+, and Django 3.0 includes built-in support for Referrer-Policy. I’ve received a lot of nice feedback for the post and the talk. Here are some of the people who’ve used it to increase their sites’ security: Kristian Glass took app.emporium.cloud to an “A” score (tweet). This site is useful for exploring the dependency graph of all package on PyPI. Çağıl Uluşahin and Ahter Somnez took their site LindyPlus to a “B” (tweet). Aidas Bendoraitis took his site 1st things 1st to an “A”, including adding a strong CSP (tweet). Tobias Kunze took Pretalx to an “A” (tweet). Thanks to all for letting me know. If you have used the guide to improve your site’s security, please email or tweet me, and I’ll add a link here! As you can see, you don’t need to get to A+, which is a lot of work. Any improvement is good for your site and users :) … -
How to Provide Test Fixtures for Django Models in Pytest
One of the most challenging aspects of writing good tests is maintaining test fixtures. Good test fixtures motivate developers to write better tests, and bad fixtures can cripple a system to a point where developers fear and avoid them all together. The key to maintaining good fixtures is to find a good balance between flexibility and usability. Good fixtures are ones that are easy to use and easy to modify. In my latest article for RealPython I share some insights on how to maintain good test fixtures for Django models using Pytest. The article covers everything from setting up Pytest for a Django project, creating test fixtures and how to create dependency between fixtures. The article focuses on a pattern called "factory as a service". Using this pattern, you can create fixture for Django models that depend on other fixtures. This makes it easier to set up data for tests and focus on the the scenario at hand rather than setting up the data. Read "How to Provide Test Fixtures for Django Models in Pytest" on RealPython ≫ How to Provide Test Fixtures for Django Models in Pytest -
How to create a Django project and a Django application
How to create a Django project To start off create a new folder for the Django project and move into it: mkdir django-quick-start && cd $_ Here I called django-quick-start the main folder that will hold the project. Pay attention, this is not the actual Django project, but just its "home". Once inside the new folder create a Python virtual environment and activate it (note, these are two distinct commands): python3 -m venv venv source venv/bin/activate Next up install Django with: pip install django When the installer is done you can create a new Django project: django-admin startproject django_quick_start . Pay attention again: django_quick_start now is the actual Django project created inside the django-quick-start folder. The name of this home folder doesn't matter, but Django projects cannot have dashes in the name. That's the reason for these underscores in django_quick_start. Pay also attention to the dot in django-admin startproject django_quick_start .. With the dot we can avoid additional folder nesting. How to create a Django application Every Django project is made of stand alone applications. Each application may have models, views, and custom logic. There is also a great choice of community applications ready to be installed in your project. … -
Django News - Bye Bye Python 2 - Apr 3rd 2020
News Django bugfix releases issued: 3.0.5 and 2.2.12 With this release, Django 1.11 has reached the end of extended support. All Django 1.11 users are encouraged to upgrade to Django 2.2 or later to continue receiving fixes for security issues. djangoproject.com Django Release Cycle A graphical guide to Django’s release cycle. jefftriplett.com New pip resolver to roll out this year The developers of pip are in the process of developing a new resolver for pip which is slated to release the second half of this year. They are asking for your help. blogspot.com Articles What the heck is pyproject.toml? Brett Cannon explains why pyproject.toml exists and why it's the future of packaging in the Python ecosystem. snarky.ca Postgres 11 and Docker Docker's Postgres image recently introduced a breaking change. This is a short tip on how to handle it. conorcunningham.net Build secrets in Docker Compose, the secure way How to build Docker images securely using "build secrets" for when you need a password to install from a private package repository yet you don't want the secret embedded in the finished image. pythonspeed.com Automating the Boring Stuff in Django Using the Check Framework How we use inspect, ast and the Django … -
Onboarding Continuity - Building SaaS #50
In this episode, we stepped from the welcome onboarding page to the first interactive page in the flow. I extracted the common banner for each of the templates and customized it for each of the steps in the process. The first thing we did was create a button on the starting page. The button connects the welcome page to the second step in the flow where the app will ask for information about the user’s school year. -
Templates For User Interfaces
In the previous Understand Django article, we looked at the fundamentals of using views in Django. This article will focus on templates. Templates are your primary tool in a Django project for generating a user interface. Let’s see how templates hook into views and what features Django provides with its template system. Set Up Templates We need a place for templates to live. Templates are static files that Django will fill in with data. -
LearnDjango.com
Weekly Django Chat NewsletterLearnDjango.comwsvincent.comDjango Slug TutorialDjango for Professionals bookDjango Caching for BeginnersDjango Markdown Tutorial -
How to Combine Two Python Decorators
Imagine you have some Django views using the same two decorators: from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_GET @require_GET @login_required def home(request): ... @require_GET @login_required def about(request): ... @require_GET @login_required def contact(request): ... It’s a bit repetitive, and prone to mistakes on new views, such as using the wrong order, or missing one. You can instead combine them into one decorator. In Python, the decorator syntax is a shortcut for calling the decorator and storing its result in the same name. For example, this snippet: @login_required def index(request): ... is the same as: def index(request): ... index = login_required(index) Therefore to combine these decorators, you can implement a new function that calls each of the decorators in turn like this. To maintain the same order, you should call them “from the inside out”. So you can make a combined decorator function like this: def require_GET_and_login(func): return require_GET(login_required(func)) You can then apply it to views like this: @require_GET_and_login def home(request): ... @require_GET_and_login def about(request): ... @require_GET_and_login def contact(request): ... Great! Some decorators take arguments, for which this technique needs expanding a bit. For example, Django’s require_http_methods is a general version of require_GET that takes an argument for the methods. If … -
Invictify - A Scheduler for Triggering Workflows
Hi there, I've recently cr... -
Using Markdown in Django
As developers, we rely on static analysis tools to check, lint and transform our code. We use these tools to help us be more productive and produce better code. However, when we write content using markdown the tools at our disposal are scarce. In this article we describe how we developed a Markdown extension to address challenges in managing content using Markdown in Django sites. Do you think they had a linter?Photo by mali maeder from Pexels Table of Contents The Problem Prior Work Using Markdown Converting Markdown to HTML Using Markdown Extensions Creating a Markdown Extension to Process Inline Links Validate and Transform Django Links Validating mailto Links Handling Internal and External Links Resolving URL Names Handling External Links Requiring Scheme Putting it All Together Conclusion Taking it Further The Problem Like every website, we have different types of (mostly) static content in places like our home page, FAQ section and "About" page. For a very long time, we managed all of this content directly in Django templates. When we finally decided it's time to move this content out of templates and into the database, we thought it's best to use Markdown. It's safer to produce HTML from Markdown, … -
Django ListView - podstawowy widok generyczny
Wyświetlanie listy, paginacja, filtrowanie, czy sortowanie to zaledwie początek tego co oferuje generyczny widok ListView w Django. Przekonaj się sam! -
Optimize Django memory usage
Django memory usage is usually quote good, but sometimes – if you use the Django ORM without really knowing what is doing behind the scenes – you can see a huge spike in RAM usage. Fortunately there exist some simple methods to optimize Django memory usage. Table of Contents 1. The problem 2. A bit of Django memory profiling 3. Optimize Django memory usage: using iterator() method 4. Optimize Django memory usage: using pagination 5. Conclusion 1. The problem Consider this is the apparently innocent view from django.http import HttpResponse from .models import FirstModel # this view will make crazy use of the RAM ;) def my_view(request): # this queryset contains about 100k records # each of them has many ForeignKeys to other models huge_queryset = FirstModel.objects.all() f = open('dumb.dump', 'w') for record in huge_queryset: print >>f, record f.close() return HttpResponse('Dumb dump completed!') as you can see it’s very simple, the peculiarity here is the dimension of the queryset, because the table contains about 100k records, and each record has several ForeignKey fields to other models. An experienced Django developer should immediately see the problem, but it can be interesting to analyze the problem a little bit more. If you … -
Django News - Issue 16 - Mar 27th 2020
News Wagtail roadmap priorities 2020 We're reviewing our roadmap for the next 12 months and we'd love your input. If you use Wagtail, please help shape our plans. google.com PyCon US 2020 in Pittsburgh, Pennsylvania is cancelled The PSF’s priority is the health and safety of the community and the COVID-19 (Coronavirus) pandemic has made it unsafe to hold PyCon US this year. blogspot.com Pipenv new release A new Pipenv release is due at the end of the month. google.com Articles Using Django Check Constraints to Ensure Only One Field Is Set From Adam Johnson, a demonstration of using check constraints in a Django model. adamj.eu How Eldarion Works Remotely — Eldarion Blog Notes on working remotely from a leading Django consultancy. eldarion.com East Meets West When Translating Django Apps Notes from a PyCascades 2020 talk on using Django's built-in translation app. automationpanda.com Postgres VIEW from Django QuerySet How (and why) to use Django's ORM to generate a Postgres VIEW. schinckel.net How to restrict access with Django Permissions A look at the various ways to implement Django permissions. coderbook.com Double-checked locking with Django ORM How to implement double-checked locking within Django. lukeplant.me.uk Designing a User-Friendly ML Platform with Django Creating … -
Starting the Onboarding Flow - Building SaaS #49
In this episode, we worked on the progress element that will display in every step of the onboarding flow. I added some labels and styled the banner using Tailwind CSS. At the end of the stream, we boxed in the shape of the welcome page with some placeholder elements. The very first thing I did was insert a top bar that was unstyled to the top of the welcome page. We added some placeholder text for each of the steps in the onboarding flow. -
Google Summer of Code - Sage Abdullah
Weekly Django Chat NewsletterGoogle Summer of Code 2020 (March 31st deadline)Sage’s GSOC proposalSage’s GSOC Blogmwparserfromhell - A Python parser for MediaWiki wikicode -
Using Django Check Constraints to Ensure Only One Field Is Set
I previously covered using Django’s CheckConstraint class to validate fields with choices and percentage fields that total 100%. Here’s another use case. A project I was working on recently stores “scores” which may have a single typed value: an integer, or a decimal, or a duration. Because they have different types, they are stored in separate columns in the database. Therefore, for a single score, only one of these columns may be filled in (not null). You could solve this by using model inheritance. The downside of this is that using either concrete or abstract inheritance, you’d need multiple tables. This is also a lot of work for a single differing field. Instead of this, we settled on a single model appraoch with multiple value columns, only one of which should be set. The model looks something like this: from django.db import models class ScoreType(models.IntegerChoices): POINTS = 1, 'Points' DURATION = 2, 'Duration' class Score(models.Model): type = models.IntegerField(choices=ScoreType.choices) value_points = models.IntegerField() value_duration = models.DurationField() (IntegerChoices is one of Django 3.0’s new enumeration types.) If type is ScoreType.POINTS, the value_points column should be set. And likewise, if the type is ScoreType.DURATION, the value_duration column should be set. However confident you are … -
More on service layers in Django
Well, that provoked some discussion. While there were plenty of people who agreed with the general idea of that post, there were also quite a few objections. And most of those seem to fall into two main categories: people who want some type of additional layer (and may or may not call it a “service”) as a way of managing cross-cutting complexity, and people who want it as an isolating abstraction for testing. There’s also a third … Read full entry -
Setting Python's Decimal Context for All Threads
Python’s decimal module has concept of a “context.” This defines the default precision of new Decimals, how rounding works, and lots of other behaviour. Maths gets complicated! It’s quite common to need to customize the decimal context, to control one of these features. As the decimal documentation states, contexts are per-thread: The getcontext() function accesses a different Context object for each thread. Having separate thread contexts means that threads may make changes (such as getcontext().prec=10) without interfering with other threads. This isolation is good, but it also means that it’s an easily forgotten concern when adding threading. This could cause hard-to-discover arithmetic bugs. Oh no! Thankfully, there’s a fix, as per the decimal documentation: [For new threads] the new context is copied from a prototype context called DefaultContext. To control the defaults so that each thread will use the same values throughout the application, directly modify the DefaultContext object. This should be done before any threads are started so that there won’t be a race condition between threads calling getcontext(). It then has this example: # Set applicationwide defaults for all threads about to be launched DefaultContext.prec = 12 DefaultContext.rounding = ROUND_DOWN DefaultContext.traps = ExtendedContext.traps.copy() DefaultContext.traps[InvalidOperation] = 1 setcontext(DefaultContext) # …