Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
filter on model

Hello, in my template i have some filters to filter items basing on each item property. Now I need to add a checkbox called "flat" which only shows items if the heel_height property value is equal to 0.

i created flat() method on models.py


class Shoe(models.Model):
    heelheight = models.IntegerField(default=0, blank=False, null=False)
    def flat(self):
        if self.heel
height == 0:
            return True
        else:
            return False


I added that field to the forms.py

class SearchForm(ModelForm):
     class Meta:
         model = Shoe
         fields = 'season', 'color', 'size', 'flat',


and i added it to my existing searchform on template

            <div class="fieldWrapper">
   

/r/django
https://redd.it/1nmqguj
📝 Focused on what I love: building and growing things📈.It's rewarding to see an idea come to life on the web. Excited about the projects ahead and always looking to learn from others in the field😊 #GrowthMindset #Tech #Innovation #PassionForWork #DigitalMarketing #WebDevelopment #OnlinePresenc

/r/django
https://redd.it/1nmna3h
Monday Daily Thread: Project ideas!

# Weekly Thread: Project Ideas 💡

Welcome to our weekly Project Ideas thread! Whether you're a newbie looking for a first project or an expert seeking a new challenge, this is the place for you.

## How it Works:

1. **Suggest a Project**: Comment your project idea—be it beginner-friendly or advanced.
2. **Build & Share**: If you complete a project, reply to the original comment, share your experience, and attach your source code.
3. **Explore**: Looking for ideas? Check out Al Sweigart's ["The Big Book of Small Python Projects"](https://www.amazon.com/Big-Book-Small-Python-Programming/dp/1718501242) for inspiration.

## Guidelines:

* Clearly state the difficulty level.
* Provide a brief description and, if possible, outline the tech stack.
* Feel free to link to tutorials or resources that might help.

# Example Submissions:

## Project Idea: Chatbot

**Difficulty**: Intermediate

**Tech Stack**: Python, NLP, Flask/FastAPI/Litestar

**Description**: Create a chatbot that can answer FAQs for a website.

**Resources**: [Building a Chatbot with Python](https://www.youtube.com/watch?v=a37BL0stIuM)

# Project Idea: Weather Dashboard

**Difficulty**: Beginner

**Tech Stack**: HTML, CSS, JavaScript, API

**Description**: Build a dashboard that displays real-time weather information using a weather API.

**Resources**: [Weather API Tutorial](https://www.youtube.com/watch?v=9P5MY_2i7K8)

## Project Idea: File Organizer

**Difficulty**: Beginner

**Tech Stack**: Python, File I/O

**Description**: Create a script that organizes files in a directory into sub-folders based on file type.

**Resources**: [Automate the Boring Stuff: Organizing Files](https://automatetheboringstuff.com/2e/chapter9/)

Let's help each other grow. Happy

/r/Python
https://redd.it/1nn7o0l
Monday Daily Thread: Project ideas!

# Weekly Thread: Project Ideas 💡

Welcome to our weekly Project Ideas thread! Whether you're a newbie looking for a first project or an expert seeking a new challenge, this is the place for you.

## How it Works:

1. **Suggest a Project**: Comment your project idea—be it beginner-friendly or advanced.
2. **Build & Share**: If you complete a project, reply to the original comment, share your experience, and attach your source code.
3. **Explore**: Looking for ideas? Check out Al Sweigart's ["The Big Book of Small Python Projects"](https://www.amazon.com/Big-Book-Small-Python-Programming/dp/1718501242) for inspiration.

## Guidelines:

* Clearly state the difficulty level.
* Provide a brief description and, if possible, outline the tech stack.
* Feel free to link to tutorials or resources that might help.

# Example Submissions:

## Project Idea: Chatbot

**Difficulty**: Intermediate

**Tech Stack**: Python, NLP, Flask/FastAPI/Litestar

**Description**: Create a chatbot that can answer FAQs for a website.

**Resources**: [Building a Chatbot with Python](https://www.youtube.com/watch?v=a37BL0stIuM)

# Project Idea: Weather Dashboard

**Difficulty**: Beginner

**Tech Stack**: HTML, CSS, JavaScript, API

**Description**: Build a dashboard that displays real-time weather information using a weather API.

**Resources**: [Weather API Tutorial](https://www.youtube.com/watch?v=9P5MY_2i7K8)

## Project Idea: File Organizer

**Difficulty**: Beginner

**Tech Stack**: Python, File I/O

**Description**: Create a script that organizes files in a directory into sub-folders based on file type.

**Resources**: [Automate the Boring Stuff: Organizing Files](https://automatetheboringstuff.com/2e/chapter9/)

Let's help each other grow. Happy

/r/Python
https://redd.it/1nn7o08
My flask web page is a blank page

Hello, I'm trying a small start with flask and web tools, I wrote a small code contain the main Flask, HTML, CSS and JS, but all i see is a white page, i tried changing the browsers but it didn't work, what could be the problem? this is my code :

Project structure :

FLASKTEST/
test.py

├── templates/
│ index.html
└── static/
style.css
script.js

**test.py** file :

from flask import Flask, rendertemplate

app = Flask(name)

@app.route("/")
def home():
return render
template("index.html")

if name == "main":
app.run(debug=True)

index.html file :

<!DOCTYPE html>
<html lang="en">
<head>


/r/flask
https://redd.it/1nmxhe5
Do you find it helpful to run Sphinx reStructuredText/Markdown in a browser?

I’ve been thinking a lot about documentation workflows lately. Sphinx is super powerful (and pretty much the standard for Python), but every time I try to onboard someone new, the initial “install + configure” step feels like a wall.

For example, if you just want to:

Test how reStructuredText or MyST Markdown renders
Show a student how Sphinx works
Experiment with docs-as-code quickly
Quickly see the resulting HTML when styling Sphinx themes

…you still need a local setup, which isn’t always trivial. Has anyone else struggled with this? How do you usually get around the “first steps” friction when teaching or experimenting with Sphinx?

(I’ve been tinkering with a little experiment in running full, latest Sphinx completely in a browser using WebAssembly — will share it in the comments if anyone’s curious.)

/r/Python
https://redd.it/1nmycfj
Trying to GET data from my DB using modal form

i want to be able to pull a data i just sent to my database using modal form to my FE. i am able to post the data from my FE to the database, but where i have an issue is if i reload the page, the page is supposed to GET the data from the DB and display it, but it doesn't. i'm pretty sure it might be something minor i'm missing but i haven't been able to solve it despite hours of debugging.

EDIT: Here's the Flask code

import datetime as dt
from flask import Flask,rendertemplate, request, urlfor
from flaskcors import CORS
import db


app = Flask(name)
CORS(app)

today =
dt.datetime.today()
# gets the data of every registered user including name and date of birth etc.
saved
birthdays= db.DateOfBirth.objects().all()



# This is the home page route to to show the active Birthdays


/r/flask
https://redd.it/1nnjihb
We just launched Leapcell, deploy 20 Python websites for free

hi r/Python

Back then, I often had to pull the plug on side projects built with Python, the hosting bills and upkeep just weren’t worth it. They ended up gathering dust on GitHub.

That’s why we created **Leapcell**: a platform designed so your Python ideas can stay alive without getting killed by costs in the early stage.

**Deploy up to 20 Python websites or services for free (included in our free tier)**
Most PaaS platforms give you a single free VM (like the old Heroku model), but those machines often sit idle. Leapcell takes a different approach: with a serverless container architecture, we fully utilize compute resources and let you host multiple services simultaneously. While other platforms only let you run one free project, Leapcell lets you run up to **20 Python apps** for free.

And it’s not just websites, your Python stack can include:

* Web APIS: Django, Flask, FastAPI
* Data & automation: Playwright-based crawlers
* APIs & microservices: lightweight REST or GraphQL services

We were inspired by platforms like Vercel (multi-project hosting), but Leapcell goes further:

* **Multi-language support:** Django, Node.js, Go, Rust.
* **Two compute modes**
* ***Serverless***: cold start < 250ms, autoscaling with traffic (perfect for early-stage Django apps).
*

/r/Python
https://redd.it/1nnh6g0
Why Django is the best backend framework for the startup and mvp projects ?

I’m a startupper. I really like using Django for this kind of projects. It’s too fast and comfortable to develop. Why do you choose Django for the MVPs ? How Django’s helped you to solve your problems ?

/r/django
https://redd.it/1nno0uk
D&D Twitch bot: Update 2!

Hello! So I posted awhile back that I was making a cool twitch bot for my chatters themed on D&D and wanted to post another update here! (OG post) https://www.reddit.com/r/Python/comments/1mt2srw/dd\_twitch\_bot/

My most current updates have made some major strides!

1.) Quests now auto generate quest to quest, evolving over time at checkpoints and be much more in depth overall. Giving chatters a better story, while also allowing them multiple roll options with skill rolls tied into each class. (Things like barbarians are bad at thinking, but great at smashing! So they might not be the best at a stealth mission in a China shop...)

2.) The bot now recognizes new chatters and greets them with fanfare and a little "how to" so they are not so confused when they first arrive. And the alert helps so I know they are a first time chatter!

3.) I got all the skill rolls working, and now they are showing and updated in real time on the display. That way chatters can see at all times which skills are the best for this adventure they are on!

4.) Bosses now display across

/r/Python
https://redd.it/1nnwn2h
python-cq — Lightweight CQRS package for async Python projects

# What My Project Does

[`python-cq`](https://github.com/100nm/python-cq) is a package that helps apply CQRS principles (Command Query Responsibility Segregation) in async Python projects.

The core idea of CQRS is to separate:

* **Commands** → actions that change the state of the system.
* **Queries** → operations that only read data, without side effects.
* **Events** → facts that describe something that happened, usually triggered by commands.

With `python-cq`, handlers for commands, queries, and events are just regular Python classes decorated with `@command_handler`, `@query_handler`, or `@event_handler`.
The framework automatically detects which message type is being handled based on type hints, no need to inherit from base classes or write boilerplate.

It also integrates with dependency injection through [`python-injection`](https://github.com/100nm/python-injection), which makes it easier to manage dependencies between handlers.

Example:

```python
from dataclasses import dataclass
from injection import inject
from cq import CommandBus, RelatedEvents, command_handler, event_handler

@dataclass
class UserRegistrationCommand:
email: str
password: str

@dataclass
class UserRegistered:
user_id: int
email: str

@command_handler
class UserRegistrationHandler:
def __init__(self, events: RelatedEvents):
self.events = events

async def handle(self, command: UserRegistrationCommand):
""" register the user """
user_id = ...


/r/Python
https://redd.it/1nnimms
Tuesday Daily Thread: Advanced questions

# Weekly Wednesday Thread: Advanced Questions 🐍

Dive deep into Python with our Advanced Questions thread! This space is reserved for questions about more advanced Python topics, frameworks, and best practices.

## How it Works:

1. **Ask Away**: Post your advanced Python questions here.
2. **Expert Insights**: Get answers from experienced developers.
3. **Resource Pool**: Share or discover tutorials, articles, and tips.

## Guidelines:

* This thread is for **advanced questions only**. Beginner questions are welcome in our [Daily Beginner Thread](#daily-beginner-thread-link) every Thursday.
* Questions that are not advanced may be removed and redirected to the appropriate thread.

## Recommended Resources:

* If you don't receive a response, consider exploring r/LearnPython or join the [Python Discord Server](https://discord.gg/python) for quicker assistance.

## Example Questions:

1. **How can you implement a custom memory allocator in Python?**
2. **What are the best practices for optimizing Cython code for heavy numerical computations?**
3. **How do you set up a multi-threaded architecture using Python's Global Interpreter Lock (GIL)?**
4. **Can you explain the intricacies of metaclasses and how they influence object-oriented design in Python?**
5. **How would you go about implementing a distributed task queue using Celery and RabbitMQ?**
6. **What are some advanced use-cases for Python's decorators?**
7. **How can you achieve real-time data streaming in Python with WebSockets?**
8. **What are the

/r/Python
https://redd.it/1no2n2e
Append-only time-series storage in pure Python: Chronostore (faster than CSV & Parquet)

# What My Project Does

*Chronostore* is a fast, append-only binary time-series storage engine for Python. It uses schema-defined daily files with memory-mapped zero-copy reads compatible with Pandas and NumPy. (supported backends: flat files or LMDB)

In benchmarks (10M rows of 4 float64 columns), *Chronostore* wrote in `~0.43 s` and read in `~0.24 s,` vastly outperforming CSV (`58 s` write, `7.8 s` read) and Parquet (`~2 s` write, `~0.44 s` read).

Key features:

* Schema-enforced binary storage
* Zero-copy reads via mmap / LMDB
* Daily file partitioning, append-only
* Pure Python, easy to install and integrate
* Pandas/NumPy compatible

Limitations:

* No concurrent write support
* Lacks indexing or compression
* Best performance on SSD/NVMe hardware

# Links

* 👉 [The GitHub repo](https://github.com/rundef/chronostore)

if you find it useful, a would be amazing!

# Why I Built It

I needed a simple, minimal and high-performance local time-series store that integrates cleanly with Python data tools. Many existing solutions require servers, setup, or are too heavy. *Chronostore* is lightweight, fast, and gives you direct control over your data layout

# Target audience

* Python developers working with **IoT, sensor, telemetry, or financial tick data**
* Anyone needing **schema-controlled, high-speed local time-series persistence**
* Developers who want **fast alternatives to CSV or Parquet for time-series data**
* Hobbyists and students exploring **memory-mapped I/O

/r/Python
https://redd.it/1nnn35x
S3Ranger - A TUI for S3 and S3-like cloud storage built using Textual

### What My Project Does
I built s3ranger, a TUI to interact with S3 and S3-like cloud storage services. It’s built with Textual and uses boto3 + awscli under the hood.
While the AWS CLI already supports most of these operations, I wanted an actual interface on top of it that feels quick and easy to use.

Some things it can do that the standard S3 console doesn’t give you:
- Download a "folder" from S3
- Rename a "folder"
- Upload a "folder"
- Delete a "folder"

### Target Audience
This project is mainly for developers who:
- Use localstack or other S3-compatible services and want a simple UI on top
- Need to do batch/folder operations that the AWS S3 web UI doesn’t provide
- Like terminal-first tools (since this is a TUI, not a web app)

It’s not meant to replace the CLI or the official console, but rather to make repetitive/local workflows faster and more visual.

--
You can run it against localstack like this:
s3ranger --endpoint-url http://localhost:4566 --region-name us-east-1

### GitHub Link
Repo: https://github.com/Sharashchandra/s3ranger

Any feedback is appreciated!

/r/Python
https://redd.it/1nnokzl
The Proper Way to Switch Django Branches with Divergent Migrations (Avoid Data Loss!)

Hey everyone,

Just spent half a day untangling a database nightmare after switching git branches without thinking about migrations. Learned a hard lesson and wanted to share the proper, safe way to do this when your branches have different migration histories.

# The Problem (The "Oh No" Moment)

You're working on a feature branch (feature-branch) that has new migrations (e.g., 0004_auto_202310...). You need to quickly switch back to main to check something. You run git checkout main, start the server, and... BAM. DatabaseErrors galore. Your main branch's code expects the database to be at migration 0002, but it's actually at 0004 from your feature branch. The schema is out of sync.

Do NOT just delete your database or migrations. There's a better way.

# The Safe Fix: Migrate Backwards Before Switching

The core idea is to reverse your current branch's migrations to a common point before you switch git branches. This keeps your database schema aligned with the code you're about to run.

# Step-by-Step Guide

1. Find the Last Common Migration

Before switching, use showmigrations to see what's applied. Identify the last migration that exists on both your current branch and the target branch.

python manage.py showmigrations yourappname

You'll see a list with [X] for applied migrations. Find the highest-numbered migration that is present on both branches. Let's say it's 0002.

2. Migrate Your Database Back to that Common State

This is the

/r/django
https://redd.it/1no2rai
StringWa.rs: Which Libs Make Python Strings 2-10× Faster?

## What My Project Does

I've put together StringWa.rs — a benchmark suite for text and sequence processing in Python. It compares str and bytes built-ins, popular third-party libraries, and GPU/SIMD-accelerated backends on common tasks like splitting, sorting, hashing, and edit distances between pairs of strings.

## Target Audience

This is for Python developers working with text processing at any scale — whether you're parsing config files, building NLP pipelines, or handling large-scale bioinformatics data. If you've ever wondered why your string operations are bottlenecking your application, or if you're still using packages like NLTK for basic string algorithms, this benchmark suite will show you exactly what performance you're leaving on the table.

## Comparison

Many developers still rely on outdated packages like nltk (with 38 M monthly downloads) for Levenshtein distances, not realizing the same computation can be 500× faster on a single CPU core or up to 160,000× faster on a high-end GPU. The benchmarks reveal massive performance differences across the ecosystem, from built-in Python methods to modern alternatives like my own StringZilla library (just released v4 under Apache 2.0 license after months of work).

Some surprising findings for native str and bytes:
`str.find` is about 10× slower than it can be
On 4

/r/Python
https://redd.it/1nocyn3
Suggest the best way to learn django

Hey guys. Im learning django on my own. I love to learn by building. But I'm facing lots of errors from django framework. Do you have any advice regarding that?

/r/django
https://redd.it/1no21k2
AttributeError
AttributeError: 'tuple' object has no attribute 'items'

from decimal import Decimal
import os
import os.path as op
from datetime import datetime as dt
from sqlalchemy import Column, Integer, DateTime
from flask import Flask, render_template, send_from_directory, url_for, redirect, request
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.event import listens_for
from markupsafe import Markup
from flask_admin import Admin, form
from flask_admin.form import rules
from flask_admin.contrib import sqla, rediscli
from flask import session as login_session
from flask_login import UserMixin, LoginManager, login_user, logout_user, login_required
from flask_bcrypt import Bcrypt
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import relationship
from sqlalchemy import select

import operator
from werkzeug.utils import secure_filename


/r/flask
https://redd.it/1no9d91
Django learning advice for web app

I'm working on a healthcare web application project this semester using Django + React + PostgreSQL. My professor has outlined requirements like multi-role authentication system (patients, doctors, admins), appointment scheduling, medical records management, doctor dashboards, prescription handling, administrative features, plus JWT authentication, role-based permissions, data encryption, and security hardening against common vulnerabilities. Also some additional features such as medication reminders and medical image/file uploading.

I'm decent with Python but pretty new to Django, and my development experience is limited - mostly just a CRUD app from my database course. Given the scope and timeline(around 15 weeks), what are the best resources to learn the technologies for the project?

Also, any advice on the ideal approach for tackling a project of this scale? Should I focus on backend first, learn everything upfront, or take a more iterative approach?

/r/django
https://redd.it/1noq728
django-vite static assets being served but not loading on an Nginx deployment

hello everyone, I also posted this on the djangolearning sub but I've been fighting with this problem for 4 whole days and I'm desperate. I'm trying to deploy a simple project on a local ubuntu server VM using docker. I have three containers, Postgres, nginx and Django. I used a lot of HTMX and DaisyUI, and on my dev environment they worked really nicely being served by a Bun dev server and using django-vite, now that I'm deploying, everything works perfectly fine, except for the static assets generated by django-vite. The weirdest part is the files are being delivered to the clients but not loading correctly (the app renders but only the static assets collected by Django, like icons, are being displayed. If I check the network tab on my devtools i see the django-vite files are being served). Any idea what could be causing this?

Here is my vite.config.mjs
```
import { defineConfig } from "vite";
import { resolve } from "path";
import tailwindcss from "@tailwindcss/vite";

export default defineConfig({
base: "/static/",
build: {


/r/django
https://redd.it/1nol7b1