Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Set Default Date For Date Hierarchy In Django Admin
Introduction When we monitor daily events from django admin, most of the time we are interested in events related to today. Django admin provides date based drill down navigation page via ModelAdmin.date_hierarchy1 option. With this, we can navigate to any date to filter out events related to that date. One problem with this drill down navigation is, we have to navigate to todays date every time we open a model in admin. Since we are interested in todays events most of the time, setting todays date as default filtered date will solve the problem. Set Default Date For Date Hierarchy Let us create an admin page to show all the users who logged in today. Since User model is already registered in admin by default, let us create a proxy model to register it again. from django.contrib.auth.models import User class DjangoUser(User): class Meta: proxy = True Lets register this model in admin to show logged in users details along with date hierarchy. from django.contrib import admin @admin.register(DjangoUser) class MetaUserAdmin(admin.ModelAdmin): list_display = ('username', 'is_active', 'last_login') date_hierarchy = 'last_login' If we open DjangoUser model in admin page, it will show drill down navigation bar like this. Now, if we drill down to … -
Set Default Date For Date Hierarchy In Django Admin
Introduction When we monitor daily events from django admin, most of the time we are interested in events related to today. Django admin provides date based drill down navigation page via ModelAdmin.date_hierarchy1 option. With this, we can navigate to any date to filter out events related to that date. One problem with this drill down navigation is, we have to navigate to todays date every time we open a model in admin. Since we are interested in todays events most of the time, setting todays date as default filtered date will solve the problem. Set Default Date For Date Hierarchy Let us create an admin page to show all the users who logged in today. Since User model is already registered in admin by default, let us create a proxy model to register it again. from django.contrib.auth.models import User class DjangoUser(User): class Meta: proxy = True Lets register this model in admin to show logged in users details along with date hierarchy. from django.contrib import admin @admin.register(DjangoUser) class MetaUserAdmin(admin.ModelAdmin): list_display = ('username', 'is_active', 'last_login') date_hierarchy = 'last_login' If we open DjangoUser model in admin page, it will show drill down navigation bar like this. Now, if we drill down to … -
Django News - Django Developers Survey 2020 - Jul 31st 2020
News Django Developers Community Survey 2020 Please take a few minutes to complete the 2020 survey and help guide the future development of Django. djangoproject.com Abigail Dogbe Awarded the PSF Community Service Award for Q1 2020 From Django Girls workshop mentee in 2017 to lead organizer of PyLadies Ghana and co-organizer of PyCon Africa 2019, Abigail received the PSF Community Service Award for Q1 2020. blogspot.com Articles How to Use Django's Parallel Testing on macOS With Python 3.8+ by Adam Johnson Speed up parallel testing via this excerpt from Adam Johnson's book Speed Up Your Django Tests. adamj.eu Is Django too slow? A look at benchmarks and concurrency in Django vs competing web frameworks. mattsegal.dev Docker & Django local development: a minimal, step-by-step guide A beginner-friendly guide to Docker and Django local development. untangled.dev A Deep Dive into PostGIS Nearest Neighbor Search PostGIS adds geographic object support to PostgreSQL and is used in the GeoDjango module. crunchydata.com XSS Exploitation in Django Applications An overview of various exploits that can work against the Django templating engine in a modern web application. github.io Writing Models in Django A nice beginner's intro to creating a model and a superuser. hashnode.dev Tutorials How to … -
Docs, Bugs, and Reports - Building SaaS #66
In this episode, I created documentation for anyone interested in trying out the application. After documenting the setup, I moved on to fixing a bug with the scheduling display of courses. In the latter half of the stream, we focused on creating a new reports section to show progress reports for students. One of my patrons requested some documentation to explain how to get started with the project. We updated the README. -
Pros and Cons of Django Web Framework
Python is the 3rd most popular programming language in 2020. It is a powerful, dynamic, syntax-simplified, programming language used for high-level web application development and machine learning apps. And if you know about Python, you’ve probably heard of Django web framework – the most used Python framework. Django development has gained much fame due to its computation […] The post Pros and Cons of Django Web Framework appeared first on BoTree Technologies. -
Create a Dark Mode hook in React.js
I love dark mode. It's definit... -
Backporting a Django ORM Feature with Database Instrumentation
Last week I covered Django’s database instrumentation, and making a wrapper that’s always installed. Here’s a different use case that I encountered last year on a project. I was helping optimize query patterns for a model - let’s call it Book. An import function used a loop to import new model instances based on a unique title field: for title in titles: Book.objects.get_or_create(title=title, defaults=...) This function took several seconds as it inserted several hundred records, required for the project to work. This was particularly noticeable at the start of tests. (Surprise, this is also a test optimization story!) We can speed up such an import with the QuerySet.bulk_create() method, passing ignore_conflicts=True. This method inserts a list of instances into the database in as few queries as possible (as little as one). The ignore_conflicts=True option skips any instance that conflicts with a unique or primary key constraint: Book.objects.bulk_create( [Book(title=title, ...) for title in titles], ignore_conflicts=True, ) This is a great solution, but unfortunately it wasn’t available. The client’s project was on Django 2.0 at the time and the ignore_conflicts argument to bulk_create() was only added in 2.2. Upgrading Django would be a rather large yak shave. Instead, I decided to backport … -
Django, Docker, and PostgreSQL Tutorial
In this tutorial we will create a new Django project using Docker and PostgreSQL. Django ships with built-in SQLite support but even for local development you are better off using … -
Django-allauth Tutorial
Django comes with a robust built-in authentication system for users but it does not provide support for third-party (social) authentication via services like Github, Gmail, or Facebook. Fortunately, the excellent … -
Django Rest Framework Tutorial: Todo API
[Django Rest Framework](http://www.django-rest-framework.org/) is a powerful library that sits on top of existing Django projects to add robust web APIs. If you have an existing Django project with only models … -
Official Django REST Framework Tutorial - A Beginners Guide
This is a beginner-friendly guide to the official Django Rest Framework [tutorial](http://www.django-rest-framework.org/tutorial/1-serialization/). If you have struggled to complete the official tutorial on your own, consider this guide a good place … -
How to Modernize a Django Index Definition with Zero Downtime
If you’ve read the Django documentation for Model.Meta.index_together recently, you may have noticed this note: Use the indexes option instead. The newer indexes option provides more functionality than index_together. index_together may be deprecated in the future. Django historically provided index control for a single field with Field(db_index=True), and for multiple fields in Meta.index_together. These are good for specifying indexes for one or more fields, but they don’t give you access to the full power of database indexes. The Meta.indexes option was added in Django 1.11 (2017) to allow use of more index features through the Index() class. Initially Index() added support for indexes with descending ordering. It now supports db_tablespace to control storage, opclasses to use PostgreSQL’s various operator classes for indexes, and condition to create partial indexes that don’t contain every row. “Upgrading” So, how do you “upgrade” from Field(db_index=True) or Meta.index_together to Meta.indexes? Well first, this isn’t necessary. Neither feature is actually deprecated, and they’re not likely to be either. If you have an old project using either Field(db_index=True) or Meta.index_together, you’re best leaving it in place and using indexes for new indexes. But this change is a good example of how to make a “zero downtime” migration, … -
How to manage logs with Django, Gunicorn and NGINX
So you want to run a Django app using NGINX and Gunicorn. Did you notice that all three of these tools have logging options? You can configure Django logging, Gunicorn logging, and NGINX logging. You just want to see what's happening in your Django app so that you can fix … -
Cool! I'm going to use it as a base for the article `Create and Deploy Django Server to the GKE`.
Cool! I'm going to use it as a base for the article `Create and Deploy Django Server to the GKE`.Haha. -
Django News - Django Turns 15 and New Releases! - Jul 24th 2020
News Django's 15th Birthday Somehow we missed this last week, but July 17th, 2005 was the public introduction of Django. Here is co-creator Simon Willison's initial blog post. As well as a 2015 talk on Django origins. simonwillison.net Django 3.1 Release Candidate This is the final chance to try 3.1 features before the release on August 3rd. djangoproject.com Python 3.8.5 and 3.9.0b5 released Python 3.8.5 released as a security hotfix. 3.9.0b5, the last beta before 3.9.0, also available blogspot.com Wagtail 2.9.3 and 2.7.4 released Wagtail 2.9.3 and 2.7.4 were released to prevent an HTML injection through form field. github.com Articles XSS Exploitation in Django Applications Anthony Shaw covers various ways to exploit the Django templating engine in a modern web application. github.io Disable Instrumentation Packages during Tests by Adam Johnson Performance tips around instrumentation like django-debug-toolbar and others that can be disabled for tests. adamj.eu Update Django template fragment caches in the background Nicolas Kuttler refactors some code that uses Django's template fragment caching to use low-level cache API. kuttler.eu What is Django (Python)? A beginner-friendly overview of Django. learndjango.com My GPG setup for developing and more If you aren't digitally signing your Git commits then this article is for … -
Is Django too slow?
Does Django have "bad performance"? The framework is now is 15 years old. Is it out of date? I mean, look at these benchmarks: NodeJS/Express is consistently getting better numbers than Django. If you are learning Django in 2020 then you might be worried that you're wasting time with … -
How to make your Django project easy to move and share
You need your Django project to be portable. It should be quick and easy to start it up on a new laptop. If it isn't portable, then your project is trapped on your machine. If it gets deleted or corrupted, then you've lost all your work! This issue comes up … -
Speaking online at EuroPython 2020
An article about my first participation as a speaker at an online conference: EuroPython 2020. -
Upcoming Courses | August 2020
After the smashing success of the Django Crash Course Live, we're running two live, online courses in August. Django Best Practices the Two Scoops Way August 14th, 2020 | 9AM-4PM PST / 4PM - 11PM UTC We're offering a live, online class called Django Best Practices the Two Scoops Way. This is a live interactive class conducted via Zoom conferencing software. Daniel is going to dive deep into Django and Python. He's going to turn on the firehose of knowledge. Best of all, this is a a live event. That means attendees can ask questions, and are encouraged to do so. Material covered includes everything from code architecture to model design to API development to bottleneck analysis to user accessibility and much more. This is not a beginner tutorial, it is meant for developers who have begun to create real projects with Django. Details: Event starts at 9AM PST (4PM UTC) and ends seven (7) hours later There will be an hour long break for lunch and short breaks every hour. Class prerequisites: Knowledge of the Python programming language Django experience beyond basic tutorials A device capable of running the Zoom meeting software. Internet fast enough to join online meetings … -
Handle Default Values - Building SaaS #65
In this episode, I updated a model to handle the default duration of new tasks. This default needed to come from the Course model instead of the CourseTask model so we had to determine how best to set that data in various forms. I also fixed some drop down selection bugs that populated a form with the wrong data. We made sure that all the code was well tested. I created a new default_task_duration field to the Course model. -
How to Make Always-Installed Django Database Instrumentation
Since version 2.0, Django has provided a hook for installing database instrumentation wrapper functions. These functions are like middleware for database queries, allowing you to inspect and rewrite SQL before it is sent to the database. There are many use cases, for example: Blocking database queries in certain blocks of code, as in the feature documentation. Tracking all queries, as in Scout APM’s python agent. Rewriting queries to add extra SQL features, as used in Django-MySQL’s query hints extensions. For this post, let’s use an example wrapper function that logs a warning for slow queries. We can implement it like this: import logging import time logger = logging.getLogger(__name__) THRESHOLD_SECONDS = 1.0 def slow_query_warner(execute, sql, params, many, context): start = time.perf_counter() result = execute(sql, params, many, context) duration = time.perf_counter() - start if duration > THRESHOLD_SECONDS: logger.warning("Slow query, took %.2f seconds: %s", duration, sql) return result Then for any block of code for which we want to log about slow queries, we can use: with connection.execute_wrapper(warn_about_slow_queries): ... A small limitation of the API is that it is only available as a context manager. This means having a wrapper function that’s installed for every single query is a little bit of a … -
EuroPython 2020
EuroPython is the official European conference for the Python programming language. -
NameError: name 'os' is not defined
If you've started a new Django 3.1+ project and are using older tutorials or guides, it's likely to come across the following error on your command line: ``` NameError: name … -
Caution About Faking Django Migrations
I ran into a problem recently when trying to reconfigure my Django project’s database. I had a DateTimeField on my model that I was updating to have null=True… -
Caution About Faking Django Migrations
I ran into a problem recently when trying to reconfigure my Django project’s database. I had a DateTimeField on my model that I was updating to have null=True and blank=True. There were no rows in this table. I was able to make the migrations, but then ran into this error when running python manage.py migrate. TypeError: expected string or bytes-like object What is This TypeError? Honestly, after my research, I’m not totally sure. I believe Django was trying to put a NULL value in that DateTime table column, but since the migration hadn’t been run, NULL values were still not allowed. I found something that made my error message go away… but also introduced a bug. Django’s Migrations Table Django’s migrations actually create a table in your database where database updates are tracked. Here’s a look at that table from one of my newer projects: postgres=# \d django_migrations Table "public.django_migrations" Column | Type | Collation | Nullable | Default ---------+--------------------------+-----------+----------+----------------------------------------------- id | integer | | not null | nextval('django_migrations_id_seq'::regclass) app | character varying(255) | | not null | name | character varying(255) | | not null | applied | timestamp with time zone | | not null | Indexes: "django_migrations_pkey" …