01 Nov 2024

feedDjango community aggregator: Community blog posts

Django News - Django Girls Turns 10 - Nov 1st 2024

News

2025 DSF Board Candidates

There are 21 individuals who have chosen to stand for election, and here is a complete list including their candidate statements.

Voting closes on November 15, 2024, at 23:59 Anywhere on Earth.

djangoproject.com

Django Girls Blog - It's our 10th birthday!

Django Girls has turned 10! We're so proud to reach this momentous milestone and of everything the community has achieved!

During the past decade, 2467 volunteers in 109 countries have run 1137 free workshops. More than 24,500 women in 593 cities have attended our events, and for many of them, Django Girls was their first step towards a career in tech.

The results speak for themselves.

djangogirls.org

Octoverse: AI leads Python to top language as the number of global developers surges

In this year's Octoverse report, Python overtook JavaScript as the most popular language on GitHub.

github.blog

PSF Fellow Nominations Q4 Due Date

PSF Fellow nominations for Q4 2024 are open until November 20th-nominate someone whose contributions to the Python community deserve recognition.

jonafato.com

Updates to Django

Today's 'Updates to Django' is presented by Abigail Afi Gbadago from Djangonaut Space!

Last week we had 21 pull requests merged into Django by 15 different contributors - including 5 first-time contributors! πŸŽ‰

Congratulations to Karol Alvarado, Abigail Afi Gbadago πŸš€ , amirreza sohrabi far, Emme Bravo πŸš€, Sarah SangerπŸš€ and tainarapalmeira πŸš€ for having their first commits merged into Django - welcome on board! β›΅

Coming in Django 5.2

Django Newsletter

Sponsored Link 1

A book about Django's asynchronous capabilities and the async protocols of the web such as WebSockets, Server Sent Events, Long Polling, GraphQL Subscriptions, Streaming, etc.

asyncdjango.com

Articles

How to Keep Up with Django

Part 20 of Eric Matthes's excellent series focuses on staying informed about Django code and community.

mostlypython.com

Should you use uv's managed Python in production?

The uv package manager can also install Python for you. Should you use this feature in production?

pythonspeed.com

Improving the New Django Developer Experience

The author of the new package, dj-beat-drop, expands on his DjangoCon US lightning talk about improving the experience for new Django developers.

epicserve.com

Start Coding Now - Empty Image Fields in Django

A short and sweet tip about Django's FileField and ImageFields.

startcodingnow.com

Django Commons

Django Commons is a new project similar (but with significant differences) to the long-standing Django Jazzband organization.

ryancheley.com

Django TemplateYaks

Emma explores a new approach to Django template tags by introducing class-based tags for easier reusability and customization, making complex template tag creation more manageable.

has-a.blog

Customize SaaS Apps with Django Tenant

Customize form options for multi-tenant SaaS apps with the new django-tenant-options package, which enables standardized, flexible forms across tenants while preserving data integrity and consistency.

jacklinke.com

Videos

Modern web apps with (almost) no JavaScript: Enhancing user experience with HTMX in Django

Learn how to significantly enhance user experience with HTMX, covering practical examples like click-to-edit interfaces, infinite scrolling, and real-time search, demonstrating how HTMX can simplify development and improve performance.

djangotv.com

Building a Data Harmonization Engine on top of Django - The Good, the Bad, and the Ugly

The story of Data Hub, a research project in epidemiology that integrated data processing pipelines in Django, fought with the documentation to build, deployed, and tried to make reusable for use-cases in other domains.

djangotv.com

Manage.py as the task runner

In this talk, we go through how to create, extend and replace existing management commands. We see how to use other programs from manage.py, setup proxy connections and integrate secrets.

djangotv.com

Sponsored Link 2

YOUR AD HERE

Our newsletter has a large and engaged audience of active email subscribers and an impressive open (59%) and click rate (29%). Django News has availability this quarter for single week ads or bundle deals.

django-news.com

Podcasts

Ep169: Python Core Developer - Mariatta Wijaya

Mariatta is a Python Core Team member, Python podcaster, and former PyCon Chair. We discuss her work with Python over the years, using Django in her day job, and her new consultancy, CMD Limes.

djangochat.com

Django News Jobs

Software Engineer (Python) - Fully remote at Bidnamic πŸ†•

Full Stack Python Developer at TeraLumen Solutions Pvt Ltd

Senior Python Engineer at Kazang a company part of the Lesaka Technologies Group

Chief Technology Officer at Torchbox

Software Engineer, Archiving & Data Services (Remote) at Internet Archive

Django Developer -- Data Science & Algo Focus | Remote at Spotter AI

Senior Python / Django Back-end Developer with Multi-Dimensional Data Analysis Experience at Scalable Path

Full-stack Python Developer at Scalable Path

Documentation platform engineer at Canonical

Django Newsletter

Projects

sjbitcode/django-admin-dracula

πŸ¦‡ Dracula theme for the Django admin. (Jeff's favorite theme)

github.com

epicserve/dj-beat-drop

A CLI for creating new Django projects.

github.com

Sponsorship

🌟 Sponsor Django News

Would you and your company be interested in reaching over 4,000 active Django developers? We have the Fall sponsorship inventory available.

Please find out more on our sponsorship page.

Thank you for being a part of our community and supporting Django News!

django-news.com


This RSS feed is published on https://django-news.com/. You can also subscribe via email.

01 Nov 2024 3:00pm GMT

30 Oct 2024

feedDjango community aggregator: Community blog posts

Python Core Developer - Mariatta Wijaya

Sponsor

30 Oct 2024 4:00pm GMT

29 Oct 2024

feedDjango community aggregator: Community blog posts

Empty Image Fields in Django

tl;dr

Django FileFields and ImageFields are stored as strings in your database. Don't use null=True with them, instead use blank=True and filter by .filter(image__exact="").

Discovering a Bug

I ran into a bug where I was trying to filter a QuerySet by image__isnull=False to determine if the image field was set. It ended up returning all objects where image was not yet set, so I did some digging.

How FileField and ImageField Look in the Database

The FileField and ImageField are both implemented in your database table as a varchar field. Note the type column from the psql display table below:

                               Table "public.myapp_mymodel"
    Column    |          Type          | Collation | Nullable |             Default
--------------+------------------------+-----------+----------+----------------------------------
 id           | bigint                 |           | not null | generated by default as identity
 image        | character varying(100) |           | not null |

This stores the relative path of the file, including your upload_to and filename.

The problem is that these strings have two values that might mean "empty": None and "".

How to Define a Model with Not Required File Fields

I had defined my model like this:

class MyModel(models.Model):
    image = models.ImageField(
        upload_to="images/",
        null=True,
        blank=True,
    )

But I should have removed the null=True option:

class MyModel(models.Model):
    image = models.ImageField(
        upload_to="images/",
        blank=True,
    )

How to Filter for Empty File Fields

Now, I still cannot filter by image__isnull, because the image field should never be set to NULL in the database and None in Python.

But I can filter by .filter(image__exact=""), which is the empty string.

Or exclude those values with .exclude(image__exact="").

29 Oct 2024 12:00pm GMT

2025 Django Software Foundation boardΒ nomination

My self-nomination statement for the 2025 Django Software Foundation (DSF) board of directors elections

29 Oct 2024 4:00am GMT

28 Oct 2024

feedDjango community aggregator: Community blog posts

Opening Django Model Files in PyMuPDF

I have been working on a file upload feature for a Django project. We use django-storages to store files in AWS S3, but we store them on the filesystem for local development.

PyMuPDF is a Python library for reading and writing PDF files. It's very fast and I've been delighted to use it.

I ran into a small issue getting my Django file uploads to work with PyMuPDF. This post will outline my notes on how I worked through it.

Opening a file from the local filesystem

Let's say we have a model SlideDeck with a FileField that stores a PDF file:

class SlideDeck(models.Model):
    pdf = models.FileField(
        upload_to="slide_decks",
        max_length="500",
    )

And a model SlideImage that stores an image for each slide in the PDF:

class SlideImage(models.Model):
    slide_deck = models.ForeignKey(
        SlideDeck,
        on_delete=models.CASCADE,
    )
    img = models.ImageField(
        upload_to="slide_decks/images",
        max_length="500",
    )

And we have a helper function to create a list of SlideImage objects from a SlideDeck object:

def _create_empty_slides(slide_deck: SlideDeck) -> list[SlideImage]:
    pdf_document = pymupdf.open(slide_deck.file.path)
    slide_img_objs = SlideImage.objects.bulk_create(
        [
            SlideImage(slide_deck=slide_deck)
            for i in range(len(pdf_document))
        ]
    )
    pdf_document.close()
    return slide_img_objs

The above works with the Django default FileSystemStorage backend. But if you're using a remote storage backend like the AWS S3 backend from django-storages, the file will not be available on the filesystem.

We are using AWS S3 and this was the error I ran into when trying to open a file with open(model_obj.file.path):

NotImplementedError: This backend doesn't support absolute paths.

Should you open with file.name or file.path?

Assuming we have a model FieldFile object:

file = model_obj.file

file.name returns the relative path to the file.

file.path returns the absolute path on the local filesystem.

We could then rewrite the above _create_empty_slides() function like this:

def _create_empty_slides(slide_deck: SlideDeck) -> list[SlideImage]:
    pdf_document = pymupdf.open(slide_deck.file.name)
    slide_img_objs = SlideImage.objects.bulk_create(
        [
            SlideImage(slide_deck=slide_deck)
            for i in range(len(pdf_document))
        ]
    )
    pdf_document.close()
    return slide_img_objs

And that would still work on the filesystem, but it's not portable to a remote storage backend. More on that later.

Opening an InMemoryUploadedFile

There's a GitHub discussion about uploaded files in PyMuPDF. The author had to specify to seek back to the beginning of the file to open it:

import pymupdf


def get_pages_of_uploaded_pdf(request: HttpRequest) -> int:
    # Get the file
    uploaded_pdf = request.FILES.get("user_uploaded_pdf")

    # Set read location
    uploaded_pdf.seek(0)

    # Open the file
    pdf_document = pymupdf.open(
        stream=uploaded_pdf.read(), filetype="pdf"
    )
    num_pages = len(pdf_document)
    pdf_document.close()
    return num_pages

Opening a file from remote storage

The PyMuPDF docs have a section on opening remote files. They outline getting the remote file content as a bytes object, and then opening the file with PyMuPDF:

import pymupdf
import requests


r = requests.get("https://mupdf.com/docs/mupdf_explored.pdf")
data = r.content
doc = pymupdf.open(stream=data)

I started to implement this in our project, but didn't want to have to check for what backend we're using every time we want to open a file.

So instead, we can leverage the default_storage class from Django to open the file:

import pymupdf
from django.core.files.storage import default_storage


def get_pages_from_pdf(slide_deck: SlideDeck) -> int:
    # Get the file bytes data
    with default_storage.open(slide_deck.file.name, "rb") as f:
        content: bytes = f.read()

    # Open the file with pymupdf
    pdf_document = pymupdf.open(stream=content)
    num_pages = len(pdf_document)
    pdf_document.close()
    return num_pages

This reads the entire file into memory as a bytes object in the content variable. If you're low on memory, this might create problems.

Opening a file with pymupdf as a context manager

We can rewrite the above function to use a context manager, automatically closing the file when we're done:

import pymupdf
from django.core.files.storage import default_storage


def get_pages_from_pdf(slide_deck: SlideDeck) -> int:
    # Get the file bytes data
    with default_storage.open(slide_deck.file.name, "rb") as f:
        content: bytes = f.read()

    # Open the file with pymupdf
    with pymupdf.open(stream=content) as pdf_document:
        num_pages = len(pdf_document)
    return num_pages

28 Oct 2024 12:00pm GMT

25 Oct 2024

feedDjango community aggregator: Community blog posts

Django News - Last chance to run for the DSF Board - Oct 25th 2024

Django Software Foundation

Why you should run for the DSF Board, and my goals for the DSF in 2025 - Jacob Kaplan-Moss

Applications are open for the 2025 Django Software Foundation Board of Directors - you can apply until October 25th. So, in this post I'll do two things: try to convince you to run for the board, and document my goals and priorities for 2025.

jacobian.org

Steering Council Wishlist for 6.X

Thoughts on what the upcoming Steering Council could/should work on.

softwarecrafts.co.uk

Updates to Django

Today 'Updates to Django' is presented by Abigail Afi Gbadago from Djangonaut Space!

Last week we had 14 pull requests merged into Django by 12 different contributors - including 3 first-time contributors πŸ‘ Congratulations to YashRaj1506 πŸš€, Ahmed Ibrahim and Justin Thurman for having their first commits merged into Django - welcome on board! πŸš€

Coming in Django 5.2

Django Newsletter

Wagtail CMS

Wagtail 6.3a0 (LTS) release notes

For the upcoming Wagtail 6.3, which is designated as a Long Term Support (LTS) release.

wagtail.org

Introducing the new starter kit for Wagtail CMS

Torchbox has released a new Wagtail News Template, designed to offer a high-performance, production-ready starter kit for Wagtail CMS, featuring a fully configured frontend and easy deployment to Fly.io.

wagtail.org

Sponsored Link 1

YOUR AD HERE

Our newsletter has a large and engaged audience of active email subscribers and an impressive open (59%) and click rate (29%). Django News has availability this quarter for single week ads or bundle deals.

django-news.com

Articles

Django from first principles, part 19 - Deploying a simple Django project.

This is the 19th post in a series about building a full Django project, starting with a single file. This series is free to everyone, as soon as each post comes out.

mostlypython.com

Django and the Python 3.13 REPL

A working solution to using the new REPL in Django.

treyhunner.com

My Django wishlist explained

A lengthy and well-explained wishlist of future features/upgrades for Django.

has-a.blog

Django's template-based form rendering: thoughts and pains

A collection of thoughts and impressions after moving to Django-native template-based form rendering with pretalx, my ~medium-sized(?) Django project.

github.com

Less htmx is More

The author's take on 2+ years of production HTMX experience.

unplannedobsolescence.com

Tutorials

Django Celery Tutorial to Background tasks

A very comprehensive tutorial on Celery, what it is, how to use it in Django projects, and several examples of different Celery tasks.

appliku.com

A Django Blog in 60 Seconds

It is more than possible with the help of the third-party package neapolitan.

learndjango.com

Videos

Django migrations, friend or foe? Optimize them for testing

Django migrations are a great tool, but after years of changes in a project they can become very numerous, slowing down tests. Is it possible to optimize them?

youtu.be

Mapping out Berlin's female history with Django and Leaflet.js

An introduction to the side project Named After Women, built with Django, Leaflet.js, and React.

youtu.be

Hypermedia driven maps

Using Django, Leaflet.js and HTMX to seamlessly manage a CRUD geolocation app.

youtu.be

Django and htmx Tutorial: Easier Web Development

An hour-long tutorial from Christopher Trudeau exploring how the htmx library can bring dynamic functionality, like lazy loading, search-as-you-type, and infinite scroll, to your Django web applications with minimal JavaScript.

youtu.be

Django News Jobs

Software Engineer (Python) - Fully remote at Bidnamic πŸ†•

Full Stack Python Developer at TeraLumen Solutions Pvt Ltd πŸ†•

Senior Python Engineer at Kazang a company part of the Lesaka Technologies Group

Chief Technology Officer at Torchbox

Software Engineer, Archiving & Data Services (Remote) at Internet Archive

Django Developer -- Data Science & Algo Focus | Remote at Spotter AI

Senior Python / Django Back-end Developer with Multi-Dimensional Data Analysis Experience at Scalable Path

Full-stack Python Developer at Scalable Path

Documentation platform engineer at Canonical

Django Newsletter

Projects

OmenApps/django-templated-email-md

An extension for django-templated-email for creating emails with Markdown.

github.com

bmispelon/django_wplogin

Enhance your Django admin login page.

github.com

Sponsorship

🌟 Sponsor Django News

Would you and your company be interested in reaching over 4,000 active Django developers? We have the Fall sponsorship inventory available.

Please find out more on our sponsorship page.

Thank you for being a part of our community and supporting Django News!

django-news.com


This RSS feed is published on https://django-news.com/. You can also subscribe via email.

25 Oct 2024 3:00pm GMT

24 Oct 2024

feedDjango community aggregator: Community blog posts

Built with Django Newsletter - 2024 Week 43

Hey, Happy Tuesday!

Why are you getting this: *You signed up to receive this newsletter on Built with Django. I promised to send you the latest projects and jobs on the site as well as any other interesting Django content I encountered during the month. If you don't want to receive this newsletter, feel free to unsubscribe anytime.

News and Updates

Sponsors

This issue is sponsored by OSIG. Well, sponsor is a strong word. It is just another project of mine that I wanted to share with you πŸ™ˆ. Fully free!

If you want an automated way for generating OG images for social media, this might be for you.

OSIG screenshot

If you want to become a real sponsor, just reply to this email or check out available options here.

Projects


From the Community


Top 3 links from last Issue

Support

You can support this project by using one of the affiliate links below. These are always going to be projects I use and love! No "Bluehost" crap here!

24 Oct 2024 1:35pm GMT

23 Oct 2024

feedDjango community aggregator: Community blog posts

Weeknotes (2024 week 43)

Weeknotes (2024 week 43)

I had some much needed time off, so this post isn't that long even though four weeks have passed since the last entry.

From webpack to rspack

I've been really happy with rspack lately. Converting webpack projects to rspack is straightforward since it mostly supports the same configuration, but it's much much faster since it's written in Rust. Rewriting things in Rust is a recurring theme, but in this case it really helps a lot. Building the frontend of a larger project of ours consisting of several admin tools and complete frontend implementations for different teaching materials only takes 10 seconds now instead of several minutes. That's a big and relevant difference.

Newcomers should probably still either use rsbuild, Vite or maybe no bundler at all. Vanilla JS and browser support for ES modules is great. That being said, I like cache busting, optimized bundling and far-future expiry headers in production and hot module reloading in development a lot, so learning to work with a frontend bundler is definitely still worth it.

Dark mode and light mode

I have been switching themes in my preferred a few times per year in the past. The following ugly bit of vimscript helps switch me the theme each time the sun comes out when working outside:

let t:light = 0
function! FiatLux()
    if t:light == 0
        :set background=light
        let t:light = 1
    else
        :set background=dark
        let t:light = 0
    endif
endfunction
nnoremap <F12> :call FiatLux()<CR>

I'm using the Ptyxis terminal emulator currently, I haven't investigated yet if there's a shortcut to toggle dark and light mode for it as well. Using F10 to open the main menu works fine though, and using the mouse wouldn't be painful either.

Helping out in the Django forum and the Discord

I have found some pleasure in helping out in the Django Forum and in the official Django Discord. I sometimes wonder why more people aren't reading the Django source code when they hit something which looks like a bug or something which they do not understand. I find Django's source code very readable and I have found many nuggets within it. I'd always recommend checking the documentation or maybe official help channels first, but the code is also out there and that fact should be taken advantage of.

Releases

23 Oct 2024 5:00pm GMT

A Django Blog in 60 Seconds

You can create a full-featured Django blog application in less than sixty seconds. Let's see how, with the help of [neapolitan](https://github.com/carltongibson/neapolitan), a new third-party package from former Django Fellow Carlton …

23 Oct 2024 2:29pm GMT

22 Oct 2024

feedDjango community aggregator: Community blog posts

Django TemplateYaks

Thursday morning, I fell into a rabbit hole... Inside the hole, there was a yak! I started shaving the yak and only then did I see it was a Django TemplateYak! A tale of a proof of concept for Class-Based Django TemplateTags

22 Oct 2024 5:00am GMT

18 Oct 2024

feedDjango community aggregator: Community blog posts

Django News - DSF Weekly Office Hours - Oct 18th 2024

News

➑️ Expression of interest: Django 6.x Steering Council elections

The DSF is seeking candidates for the upcoming Django Steering Council 6.x elections-interested individuals can fill out this form to express interest or get feedback on their eligibility.

google.com

Why Django supports the Open Source Pledge

Sentry is one of several partners who have launched the Open Source Pledge, a commitment for member companies to pay OSS maintainers meaningfully for their work.

djangoproject.com

Python Insider: Python 3.14.0 alpha 1 is now available

It's now time for a new alpha of a new version of Python.

blogspot.com

Django Software Foundation

Announcing weekly DSF office hours

The Django Software Foundation is opening up weekly office hours, Wednesdays at 6PM UTC, to work on and discuss various DSF initiatives.

djangoproject.com

2025 DSF Board Nominations

Nominations for the Django Software Foundation are OPEN until October 25th. There have been a host of articles about what the next Board might accomplish to help progress Django. Consider applying!

djangoproject.com

DSF initiatives I'd like to see

Former Django Fellow Carlton Gibson weighs in with his top three initiatives the new Django Software Foundation Board could work on.

noumenal.es

Updates to Django

Today 'Updates to Django' is presented by Velda Kiara from Djangonaut Space!

Last week we had 23 pull requests merged into Django by 17 different contributors - including 7 first-time contributors! Congratulations to Calvin Vu, Mario Munoz πŸš€, Meta Petric, Ekin ErtaΓ§, gabn88, Antoliny Lee, and Bona Fide IT GmbH for having their first commits merged into Django - welcome on board 🌟!

Python 3.13 was released on October 7th and Django 5.1.3 is already compatible! We also have asynchronous authentication backends added in Django 5.2.

On the community front, Djangonaut Space Session 3 has officially launched into orbit πŸš€!

Django Newsletter

Articles

Deploying a Django app with Kamal, AWS ECR, and Github Actions - Dylan Castillo

A comprehensive guide on deploying a Django application using Kamal, AWS ECR, and GitHub Actions, covering VPS preparation, Dockerfile creation, AWS configuration, Kamal setup, and automation of the deployment process.

dylancastillo.co

Proposal for a Django project template

A take on what could be a project template for Django advanced usage, with modern tooling (for Python and UI dependencies, as well as configuration/environment management), but not too opinionated.

guillot.me

Building an automatically updating live blog in Django

Django co-creator Simon Willison wrote a live blogging app for OpenAI's DevDay event.

simonwillison.net

Two weeks with uv - Oliver Andrich

Why the author is fully sold on uv two weeks after switching from Poetry, despite some known quirks.

andrich.me

Revisiting Django Built to Last

Tim Schilling reflects on the growing momentum in the Django community around fostering new contributors and maintaining reliability, as highlighted at DjangoCon US 2024.

better-simple.com

Perks of Being a Python Core Developer

Curious what it means to be a Python core developer? Mariatta lays it all out here in this detailed post.

mariatta.ca

How I do Django APIs in PyCharm

Paul Everitt walks through how he builds APIs in Django, taking advantage of various PyCharm special features.

jetbrains.com

Django + Postgres: The Hunt for Long Running Queries

Using django-pgactivity for application-level monitoring of database queries.

substack.com

Videos

Django Day Copenhagen 2024

The full playlist from this year's Django Day is now available on YouTube.

youtube.com

EuroPython 2024 - YouTube

The videos from EuroPython 2024, held in Prague, the Czech Republic July 8-14th are now available.

youtube.com

Raffaella Suardini - From junior developer to Django contributor: My open source journey

Raffaella discusses how the Djangonaut Space program transformed her professional path from a junior developer to an active member of the Django community.

✨ Raffaella is also a frequent author of our 'Updates to Django' section on Django News. πŸ‘

djangotv.com

Podcasts

Thibaud Colas - 2025 DSF Board Nominations

Thibaud is a Django Software Foundation Board Member (Secretary) and serves on the Django accessibility team. He is also on the core team for Wagtail and works at Torchbox. We discuss the current status of Django, the upcoming DSF Board elections, opportunities available for community members, and more.

djangochat.com

Django News Jobs

Senior Python Engineer at Kazang a company part of the Lesaka Technologies Group πŸ†•

Chief Technology Officer at Torchbox πŸ†•

Software Engineer, Archiving & Data Services (Remote) at Internet Archive

Django Developer -- Data Science & Algo Focus at Spotter AI

Senior Python / Django Back-end Developer with Multi-Dimensional Data Analysis Experience at Scalable Path

Full-stack Python Developer at Scalable Path

Documentation platform engineer at Canonical

Senior Full Stack Developer at Baserow

Django Newsletter

Projects

anexia-it/django-rest-passwordreset

An extension of Django REST Famework, providing a configurable password reset strategy.

github.com

SmileyChris/easy-thumbnails

Easy thumbnails for Django.

github.com

Sponsorship

🌟 Support Django News

Would you and your company be interested in reaching over 4,000 active Django developers? We have the Fall sponsorship inventory available.

Please find out more on our sponsorship page.

Thank you for being a part of our community and supporting Django News!

django-news.com


This RSS feed is published on https://django-news.com/. You can also subscribe via email.

18 Oct 2024 3:00pm GMT

Why you should run for the DSF Board, and my goals for the DSF in 2025

Applications are open for the 2025 Django Software Foundation Board of Directors - you can apply until October 25th. So, in this post I'll do two things: try to convince you to run for the board, and document my goals and priorities for 2025.

18 Oct 2024 5:00am GMT

Epic Debugging, Hilarious Outcome - Building SaaS #205

In this episode, I dug into an issue with sign up. What I thought was going to be a minor issue to fix turned into a massively intense debugging session. We ended up going very deep with the django-allauth package to understand what was going on.

18 Oct 2024 5:00am GMT

Epic Debugging, Hilarious Outcome - Building SaaS #205

In this episode, I dug into an issue with sign up. What I thought was going to be a minor issue to fix turned into a massively intense debugging session. We ended up going very deep with the django-allauth package to understand what was going on.

18 Oct 2024 5:00am GMT

17 Oct 2024

feedDjango community aggregator: Community blog posts

Getting RequestContext in Your Templates

Lately, we've been taking over projects from people who began building their first site in Django, but either got in over their head or just found they didn't have the time to continue. As I review the existing code, the first issue I typically see is using the render_to_response shortcut without including the RequestContext, preventing context processors from being used in the templates. The standard symptom is when people can't access MEDIA_URL in their templates.

Here are a few ways to add RequestContext to your templates.

Option #1: Adding RequestContext to render_to_response

The Django documentation recommends passing RequestContext as an argument to render_to_response like this:

from django.shortcuts import render_to_response
from django.template import RequestContext

def my_view(request):
# View code here...
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))

This works, but as you can see, it adds a fair amount of repetitive code to your views.

Option #2: Wrapper for render_to_response

Don't repeat yourself. Create a wrapper like this, courtesy of Django Snippet #3

from django.shortcuts import render_to_response
from django.template import RequestContext

def render_response(req, *args, **kwargs):
kwargs['context_instance'] = RequestContext(req)
return render_to_response(*args, **kwargs)

Option #3: Use Generic Views

Django's generic views include RequestContext by default. Although the docs show them being used in urls.py, you can just as easily use them in your views. James Bennet gave some examples of this technique on his blog back in '06. It looks something like this:

from django.views.generic import list_detail

def my_view(request):
# View code here...
return list_detail.object_list_(request,
queryset=Foo.objects.all(),
extra_context=some_dict)

Most views can be distilled down to either a single object or list of objects with some extra variables thrown in. When they can't, simply use direct_to_template.

Option #4: Getting Creative with Decorators

I came across a technique I hadn't seen before a couple of days ago when poking around django-cashflow. It monkey patches render_to_response using option #1 above, then creates uses a decorator for it. The code looks like this:

def render_to(template_name):
def renderer(func):
def wrapper(request, *args, **kw):
output = func(request, *args, **kw)
if not isinstance(output, dict):
return output
return render_to_response(request, template_name, output)
return wrapper
return renderer

@render_to('my_template.html')
def my_view(request):
# View code here...
return some_dict

Pretty slick.

How About You?

I use generic views for a few of reasons.

So how about you? What technique do you use and why?

17 Oct 2024 10:09pm GMT

Django for Hire

Lincoln Loop has been in "head down" mode for the last couple months. In addition to being knee deep in client projects, we have grown from a one-man development studio to a full-fledged Django development shop/consultancy. We are proud to announce that Lincoln Loop is the first (that we know of) company focusing solely on Django application development. Our development team is currently five strong and oozing with talent. Each member contributes to the community in blog posts or open source add-ons; a few of us have contributed code to Django itself. More on our dev team in the near future.

We went through the typical growing pains during the transition, but the kinks are worked out and we can officially say that we are open for business. Django projects big and small, send them our way. Our devs can handle nearly anything.

You name it, if it is Django related, we can probably help. Don't be shy, drop us a line.

17 Oct 2024 10:09pm GMT