Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django Sitemap Tutorial
A vital part of modern SEO (Search Engine Optimization) is to have a sitemap, an XML file that tells a search engine how often a page is updated and how … -
Django Email/Contact Form Tutorial
Let's build a simple contact form that sends email for a Django 4.1 website. We can take advantage of Django's built-in [email support](https://docs.djangoproject.com/en/dev/topics/email/) to make this relatively painless and then … -
Django Favicon Tutorial
This tutorial explains how to add a favicon to a Django website. The trick is it requires configuring your `static` files properly. To start things off, create a local directory … -
Django Polls Tutorial API
The [polls tutorial](https://docs.djangoproject.com/en/dev/intro/tutorial01/) is the official guide to Django. As a fun exercise, I wanted to show how little code it takes to transform it into a robust API using … -
Django in Production - III
Third part of the series covering how to get your django project into production -
Django in Production - III
Third part of the series covering how to get your django project into production -
Linode Object Storage for Django Static Files
Pushing Django into production... -
Auto Generate Django Models
Learn how to take a scraped da... -
Django News - Python 3.9 support for Django, Wagtail 2.11, and DRF 3.12.2. - Nov 6th 2020
News Django bugfix releases issued: 3.1.3, 3.0.11, and 2.2.17 Now with Python 3.9 support and a number of bug fixes. djangoproject.com Django REST framework 3.12.2 Released Bugfix release. django-rest-framework.org Wagtail 2.11 Released Lots of new features and bugfixes. github.com Events DjangoCon US 2020 Virtual A short video from DjangoCon US participants on what makes the conference so special. defna.org DjangoCon Europe 2021 DjangoCon Europe is tentatively planned for June 2-6, 2021 in Porto, PT. djangocon.eu PyCascades 2021 - Call for Papers PyCascades Remote CFP is open through November 10th, 2020. pretalx.com Django SF Virtual Meetup - November 10th Three deep technical talks on using feature flags, django-capture-on-commit-callbacks, and a view outside the technical bubble by the founder of Bradfield CS. meetup.com Articles MDN Web Docs evolves! Lowdown on the upcoming new platform Moving from Django to a JAMStack for the next version of MDN web docs, though keeping Django's auth pattern. mozilla.org Five Advanced Django Tips A look at Q objects, prefetch/select related, custom query sets, and more. laac.dev Understand Django - User Authentication A look at Django's built-in user authentication system, how auth is set up and what the default User model is. mattlayman.com Speeding Up Django Pagination Some … -
Detecting N+1 queries in Django with unit testing
When it comes to surfacing up N+1 problems in Django you have a lot of options. For one, you can use the debug toolbar which is kind enough to show duplicate queries in the SQL inspector: There is also the nplusone package, which does an amazing job at detecting N+1 queries. If instead you're lazy like me, you can use a unit test to detect N+1 queries, without installing any other package. Understanding N+1 and defining a baseline First off, you may want to define a baseline: how many queries should a view run in optimal conditions? Consider the following model for example: class Activity(models.Model): machine = models.ForeignKey(to=Machine, on_delete=models.PROTECT) def __str__(self): return f"Activity on {self.machine.hostname}" It has a foreign key to another model, Machine (not shown here). In addition, when we reference any instance of this model from within a template, its __str__ method builds a string based from the hostname property of the related model. This should immediately raise a red flag: it is a potential N+1 problem. To put things in context, imagine that in the view I select the machine_set for the current user with (machines are also tied to each user): # I'm inside a get_context_data … -
Create A Form Template - Building SaaS #78
In this episode, I created a template for one of my new forms on the new social media app that I’m building. We talked about context data, template styling, and special considerations for forms in templates. I had an empty template for the invite sending form to begin. I filled in a first attempt at the template with a header and displaying form errors. While building that, I added some context information that was needed for the display. -
My Favorite Technical Blogs and Mailing Lists
I keep up with what's happening in my field by following a number of blogs and an occasional email list. I don't read everything posted in all of these, but by scanning the topics in a feed reader, I can keep up with what's going on, without wasting a lot of time. The Caktus Group Blog Caktus's technical blog called "Developer Access," which you're reading now, regularly includes detailed technical posts based on our experience building and deploying complex websites and web apps. (Full disclosure: Of course, I write for it, as do many other Caktus employees.) Hacker News Daily Hacker News Daily is a helper for following the Hacker News site, which links to information all over the Internet ranging from interesting new software, to life as a developer, to the interaction between government and the technology business. Hacker News can be a big time sink if you try to follow it directly. Instead, the Hacker News Daily blog helps by daily posting a list of the top ten articles on Hacker News that haven't appeared there previously. Bulletproof TLS Newsletter The Bulletproof TLS Newsletter is an email list, not a blog. Messages are sent monthly, and cover the … -
Django: detail view must be called with pk or slug
Welcome back to another episode of my Django mini-tutorials! In this post we see how to deal with UUID as URLs in Django. Lately I've been experimenting with UUID as public identifiers in my Django URLs, an approach suggested in Two Scoops of Django, which incidentally I recall also having read from REST in practice, an old book from 2010. This technique consists of URLs made out from opaque identifiers, such as random numbers, or better, UUID. The goal is to obscure the model's primary key in your URLs. Opaque URLs in Django Let's see opaque URLs in practice. First off, in the templates you build your links as follows: // IMAGINE A FOR LOOP! <a href="{% url "ticket-detail" ticket.uuid %}">{{ ticket.subject }}</a> <a href="{% url "ticket-detail" ticket.uuid %}">{{ ticket.subject }}</a> This template can be served from a ListView for example, to render a list of models. Here ticket-detail is a named Django view, configured in URLconf as follows: urlpatterns = [ path( "tickets/<uuid:uuid>/", TicketDetail.as_view(), name="ticket-detail", ), ] As a path for the view we accept the uuid argument. The uuid field must be present in the model: class Ticket(models.Model): uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) # Other fields ... This … -
Retrieving related data in Django
All applications are different. However some themes keep coming up. One such theme is retrieving data from several tables. Tables related using one-to-many and many-to-many relationships. Since this post is inspired by Django’s own docs, it builds on the Pizza and Topping example entities to demonstrate a typical many-to-many relationship. I.e. a Pizza has one-to-many Toppings. And a Topping can be on one-to-many Pizzas: Initial Entity-Relationship Diagram The code for this experiment Is at this github repo. The repo’s commits show the progress made towards acheving the final code. Note that this experiment was done in order to compare django model bakery and factory boy. That post is still in progress. Classifying a Pizza as (VG) or (V) (VG) stands for vegan, (V) for vegetarian. We want to determine an attribute of a related entity, based on a property of another entity related by a many-to-many relationshp. Interesting. I.e. Let’s write the logic down: A Pizza is vegan (VG) if all its Toppings are vegan. A Pizza is vegetarian (V) if all its Toppings are vegan or vegetarian. The approach to set a Topping as vegan or vegetarian is by using an IntegerField with choices: class Topping(models.Model): VEGAN = 0 … -
Debugging async Django under Uvicorn with Pycharm
If you deploy Django async under ASGI, chances are you need an ASGI server like Uvicorn. In production, you can use Uvicorn with Gunicorn, but in development you might want to use Uvicorn standalone, which can also run programmatically from a Python script. This gives also the ability to debug your asynchronous Django project locally with any IDE. In this short guide you'll learn how to debug Django under Uvicorn with Pycharm. Running Uvicorn programmatically As a first step, create a Python script in your project root. I call mine server.py. In this file we import and run Uvicorn: import uvicorn if __name__ == '__main__': uvicorn.run("async_django.asgi:application", reload=True) Here I assume we have a Django project in the async_django folder, where we can also find a file named asgi.py, which is the ASGI application for our Django project. Once the script is ready we move to configure Pycharm. Configuring Pycharm to debug Django In Pycharm, open up the Run menù and click on Edit configurations. Here we create a new configuration for Python, to run our server.py: The Script path configuration should point to the path where server.py lives. Once done you're ready to debug your Django async project. Debugging async … -
Managing a Django Project with Poetry
Poetry is relatively new packaging and dependency manager. It makes it very easy to upload libraries to PyPI, manage dependencies visually, and has a couple of handy features. Today, I'm not going to do a deep dive into how Poetry works and all its features. Today I just want to focus on how to configure it for a Django project. -
Django: adding extra context data to a CreateView
Welcome back to another episode of my Django mini-tutorials! In this post we see how to add extra context data to a Django CreateView. What context there is in a CreateView? I already touched CreateView in this tutorial. In brief, CreateView is a Django class-based view complete of everything you need to create HTML forms in your Django pages. Here's how a CreateView looks like: class TicketCreate(CreateView): model = Ticket fields = ["subject", "message", "priority", "attachment"] success_url = reverse_lazy("clientarea") In this class-based view you specify a model to operate on, the fields you want to expose, and an optional success_url to redirect the user to, once the form has been successfully submitted. Now, a CreateView usually renders also a default template (unless you change it), which by convention takes the name of the model, followed by the word "form". For this CreateView for example, the template is ticket_form.html, which should be created beforehand in the template folder. Once rendered, the template gets a context, which in this case will include a form object which we can then render in the template. So, CreateView renders a form for editing the model, what if we want to include extra context data? Adding … -
Django News - New Django Girls Leadership - Oct 29th 2020
News Ola & Ola step down from Django Girls Foundation The Django Girls Foundation welcomed a new team of trustees: Anna, Aisha, Claire, Leona, and Rachell ❤️. djangogirls.org Python Software Foundation News: Python Software Foundation Fellow Members for Q3 2020 🎉 Congratulations to Katia Lira (DEFNA Board member), Mariatta Wijaya (DjangoCon US Keynote speaker), and other Pythoniasts for being picked as PSF Fellow Members. blogspot.com DjangoCon US 2020 Video ⏰ The deadline has been extended. Please take a minute to record a short video for the virtual conference this year. defna.org Articles A Django REST API in a Single File The third in a series of writing Django apps in a single file, following previous posts on synchronous and asynchronous use cases. adamj.eu How to Setup Django with React A detailed guide to the various steps required to have React play well with Django. mattsegal.dev Password Reset Views in Django Learn how to setup password reset views with django.contrib.auth. dev.to Podcasts PythonBytes #204 - Take the PSF survey and Will & Carlton drop by Django Fellow Carlton Gibson and DSF Board Member Will Vincent talk about moving from prototype to production in Django as well as all things deployment. pythonbytes.fm … -
Sending Invites - Building SaaS #77
In this episode, I worked on the form that will send invites to users for the new social network app that I’m building. We built the view, the form, and the tests and wired a button to the new view. The first thing that we do was talk through the new changes since the last stream. After discussing the progress, I took some time to cover the expected budget for the application to get it to an MVP. -
MongoDB - Aaron Bassett
@aaronbasett on TwitterAaron on GithubHTTP Headers from ~10 Million domains - An Open DatasetRealmWildAid AppEverything You Know About MongoDB is WrongCan You Keep a Secret? PyConline AU 2020django-loginasdjango-hijackSupport the ShowOur podcast does not have a sponsor and is a labor of love. To support the show, please consider purchasing one of the books on LearnDjango.com or suggest one to a friend. -
Generating random avatar images in Django/Python
tl;dr; <img src="/avatar.random.png" alt="Random avataaar"> generates this image: (try reloading to get a random new one. funny aren't they?) When you use Gravatar you can convert people's email addresses to their mugshot. It works like this: <img src="https://www.gravatar.com/avatar/$(md5(user.email))"> But most people don't have their mugshot on Gravatar.com unfortunately. But you still want to display an avatar that is distinct per user. Your best option is to generate one and just use the user's name or email as a seed (so it's always random but always deterministic for the same user). And you can also supply a fallback image to Gravatar that they use if the email doesn't match any email they have. That's where this blog post comes in. I needed that so I shopped around and found avataaars generator which is available as a React component. But I need it to be server-side and in Python. And thankfully there's a great port called: py-avataaars. It depends on CairoSVG to convert an SVG to a PNG but it's easy to install. Anyway, here's my hack to generate random "avataaars" from Django: import io import random import py_avataaars from django import http from django.utils.cache import add_never_cache_headers, patch_cache_control def avatar_image(request, seed=None): if … -
Generating random avatar images in Django/Python
tl;dr; <img src="/avatar.random.png" alt="Random avataaar"> generates this image: (try reloading to get a random new one. funny aren't they?) When you use Gravatar you can convert people's email addresses to their mugshot. It works like this: <img src="https://www.gravatar.com/avatar/$(md5(user.email))"> But most people don't have their mugshot on Gravatar.com unfortunately. But you still want to display an avatar that is distinct per user. Your best option is to generate one and just use the user's name or email as a seed (so it's always random but always deterministic for the same user). And you can also supply a fallback image to Gravatar that they use if the email doesn't match any email they have. That's where this blog post comes in. I needed that so I shopped around and found avataaars generator which is available as a React component. But I need it to be server-side and in Python. And thankfully there's a great port called: py-avataaars. It depends on CairoSVG to convert an SVG to a PNG but it's easy to install. Anyway, here's my hack to generate random "avataaars" from Django: import io import random import py_avataaars from django import http from django.utils.cache import add_never_cache_headers, patch_cache_control def avatar_image(request, seed=None): if … -
Application Examination
Full show notes are available at https://www.mattlayman.com/django-riffs/9. -
How to setup Django with React
It's not too hard to get started with either Django or React. Both have great documentation and there are lots of tutorials online. The tricky part is getting them to work together. Many people start with a Django project and then decide that they want to "add React" to it … -
Django News - Some of our favorite DjangoCon Europe 2020 videos - Oct 23rd 2020
News Sponsor @python on GitHub Sponsors The PSF joined GitHub's sponsor's program. Their goal is to raise enough money to help support the development of CPython. github.com Events PyTexas 2020 Schedule PyTexas is this weekend, Oct 24th & 25th, and is free to attend. Donations and t-shirts may still be available. pytexas.org San Francisco Django Virtual Meetup Join the San Francisco Django Meetup Group on October 28th for a free virtual meetup. meetup.com Articles A Year in the Life of a DSF Board Member An overview of 2020 activities for the Django Software Foundation Treasurer position. wsvincent.com Why You Should Pay for Open Source Will Heinemann discusses making a strong case for supporting (and paying for) open-source and a recent Wagtail Space 2020 video on the topic. wagtail.io Simplifying Django deployments on Heroku Eric Matthes, author of Python Crash Course, on his newly created Heroku Python buildpack that automates as much of the deployment process as possible ehmatthes.com Comprehending Class-Based Views in Django - Creating a CBV The second in a series of articles on how CBVs work under-the-hood. brennantymrak.com feincms may still be relevant feincms is one of the original Django CMS's and still in use. This article highlights …