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
(noob q) What's the best way to set up a many-to-many relationship with djangorestframework?

To simplify the scenario:

My app has users and pre-defined cards. Users can build decks using the cards that are available.

So of course I need models for User, Deck, and Card.

Each User:Deck is 1:many - easy, add foreign key to Deck for User/owner

Here's where I'm not sure what the best option is:
Each Deck includes many cards, and each card may belong to many decks.
Should I build a list of cards that belong to the deck, then include them as a single field? (I think this would be slower because I'd have to retrieve the list then query for those cards?)
Or should I build a separate table that has a separate row for each deck-card relation? (So I would take Deck ID, filter DeckCards by deck ID, and all the cards listed are available)

I'm learning about serializers and hyperlinking right now, but not sure what would be the best way to set up my API here. I followed through the DRF tutorial and it looks like they used hyperlinking for 1:many (users:snippets) but not sure if I can do it the same way for many:many.

/r/django
https://redd.it/1hiuol0
[Release 0.4.0] TSignal: A Flexible Python Signal/Slot System for Async and Threaded Python—Now with

Hey everyone!

I’m thrilled to announce TSignal 0.4.0, a pure-Python signal/slot library that helps you build event-driven applications with ease. TSignal integrates smoothly with async/await, handles thread safety for you, and doesn’t force you to install heavy frameworks.

# What’s New in 0.4.0
## Weak Reference Support
You can now connect a slot with weak=True. If the receiver object is garbage-collected, TSignal automatically removes the connection, preventing memory leaks or stale slots in long-lived applications:

```python
# Set weak=True for individual connections
sender.event.connect(receiver, receiver.on_event, weak=True)

# Or, set weak_default=True at class level (default is True)
@t_with_signals(weak_default=True)
class WeakRefSender:
@t_signal
def event(self):
pass

# Now all connections from this sender will use weak references by default
# No need to specify weak=True for each connect call
sender = WeakRefSender()
sender.event.connect(receiver, receiver.on_event) # Uses weak reference

# Once `receiver` is GC’d, TSignal cleans up automatically.
```

## One-Shot Connections (Optional)
A new connection parameter, one_shot=True, lets you disconnect a slot right after its first call. It’s handy for “listen-once” or “single handshake” scenarios. Just set:

```python
signal.connect(receiver, receiver.handler, one_shot=True)
```

The slot automatically goes away after the first emit.

## Thread-Safety Improvements
TSignal’s internal locking and scheduling mechanisms have been refined to further reduce race conditions in high-concurrency environments. This ensures more

/r/Python
https://redd.it/1hj9cjs
Any suggestions to my plan to learn Django?

For a bit of background, I'm a software engineer with 2+ professional YoE exclusively in Python for small scale applications, with some basic experience in FastAPI, MongoDB, PostgreSQL, PyQt and Docker. I would say I'm fairly proficient in core python but virtually no knowledge/experience in the fundamentals of the internet/HTTP/DNS/networking/cloud deployment, etc.

I'm really interested in learning Django which stems from my goal to build a web app that I have in mind + land a Django role in the distant future, whilst also hoping that the aforementioned weak areas will be learnt along the way.

As I'm in no real rush to learn Django and build my idea, I'd like to plan out some reading material hoping to comprehensively cover the main areas, including deployment, payment handling, etc. So, I'm not really interested in the 5-hour speedrun courses on youtube.

I also don't like the idea of jumping head first into building my idea, as I've taken that approach before and it resulted in a lot of undue stress from incessant jumping around which could've been avoided if I learnt things in a intuitively structured way. Also, I do plan on using the django docs for

/r/django
https://redd.it/1hjm9rl
Volunteer for a google meet

Hi ! As the title says, i'm looking for a flask developer to volunteer for an interview through google meet.
I teach some university students web development using flask , and i thought it's a good idea to get one of those developers to come into one of our regular meets

You will basically get asked some questions regarding web development,
If you are interested, send a PM
Anyone's help is much appreciated.

Ps : i'll be happy to answer any questions down below

/r/flask
https://redd.it/1hjjxql
Sunday Daily Thread: What's everyone working on this week?

# Weekly Thread: What's Everyone Working On This Week? 🛠️

Hello /r/Python! It's time to share what you've been working on! Whether it's a work-in-progress, a completed masterpiece, or just a rough idea, let us know what you're up to!

## How it Works:

1. Show & Tell: Share your current projects, completed works, or future ideas.
2. Discuss: Get feedback, find collaborators, or just chat about your project.
3. Inspire: Your project might inspire someone else, just as you might get inspired here.

## Guidelines:

Feel free to include as many details as you'd like. Code snippets, screenshots, and links are all welcome.
Whether it's your job, your hobby, or your passion project, all Python-related work is welcome here.

## Example Shares:

1. Machine Learning Model: Working on a ML model to predict stock prices. Just cracked a 90% accuracy rate!
2. Web Scraping: Built a script to scrape and analyze news articles. It's helped me understand media bias better.
3. Automation: Automated my home lighting with Python and Raspberry Pi. My life has never been easier!

Let's build and grow together! Share your journey and learn from others. Happy coding! 🌟

/r/Python
https://redd.it/1hjmlmy
PyMo - Python Motion Visualizer CLI

Hello, I have build a motion visualizer in python as a CLI script.

What My Project Does: It extracts frames from a video, offsets them and blends them using difference (blend mode from Image and Video Editing Software), applies a few filters and exports a new video.

Target Audience: This is for anyone willing to use it, mostly for fun. If you are comfortable with running scripts in a terminal, you are the target audience. I have mostly created it to see the movement of my vape clouds and that is fun and interesting.

Comparison: As this process can be achieved in any video editing software, even blender, there is not much of a comparison. The only thing that my project does, is the post processing. It just runs contrast and denoise, but that brings out details, which video editing software mostly won't give you (At least from my experience).

This was just a fun project for me which got me to learn and understand tqdm and opencv2.

Check it out at my Github Repo: https://github.com/TheElevatedOne/pymo

/r/Python
https://redd.it/1hjjson
Django Custom User Model Migration Issue - "Lazy Reference to 'users.CustomUser'"

Hello, I'm working on a Django project where I've implemented a custom user model by subclassing AbstractUser. In my `settings.py`, I've correctly set AUTH_USER_MODEL = 'users.CustomUser'. However, when I run the migrations, I get the following error:
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'users.customuser', but app 'users' doesn't provide model 'customuser'.

I’ve already made sure that the CustomUser model is correctly defined in users/models.py, and the app is listed in INSTALLED_APPS. I've also run makemigrations for the users app, but I’m still encountering this issue.

Has anyone experienced this before or can help me figure out why Django can't find the CustomUser model? Any advice would be greatly appreciated!

/r/django
https://redd.it/1hjuz9e
Any tips to improve my simple "game"

hey, i did the ib diploma in highschool and for my computer science project i made a simple 2d game, but due to deadlines i kinda rushed it, (here is the github link) now that i finished highschool i have more time and id like to redo it from scratch and do something that im proud of, if you could give me any tips on what i could add and how to improve it it would be extremely helpful, thank you everyone and have a wonderful weekend.

/r/Python
https://redd.it/1hjbdai
Spotipy - has anyone used it before?

Hi all -


Has anyone used Spotipy? I'm just a bit concerned that I'd be giving my username and password to something I haven't wrote myself - I'm used to using random scripts off github, but it gives me pause to hand over my details


am I just being silly?

/r/Python
https://redd.it/1hjkpex
Pivot from Flask

Hey everyone,

I recently built an app using Flask without realizing it’s a synchronous framework. Because I’m a beginner, I didn’t anticipate the issues I’d face when interacting with multiple external APIs (OpenAI, web crawlers, etc.). Locally, everything worked just fine, but once I deployed to a production server, the asynchronous functions failed since Flask only supports WSGI servers.

Now I need to pivot to a new framework—most likely FastAPI or Next.js. I want to avoid any future blockers and make the right decision for the long term. Which framework would you recommend?

Here are the app’s key features:

Integration with Twilio
Continuous web crawling, then sending data to an LLM for personalized news
Daily asynchronous website crawling
Google and Twitter login
Access to Twitter and LinkedIn APIs
Stripe payments

I’d love to hear your thoughts on which solution (FastAPI or Next.js) offers the best path forward. Thank you in advance!

/r/flask
https://redd.it/1hjul50
Creating my own password manager bc I can

I started off with creating a CLI app and want to slowly move into making a desktop app, a web app, and a mobile app so I can just host my db and encryption key somewhere and be done with it. I was wondering if anyone can take a peek and give me some criticisms here and there since I don't normally create apps in python: https://github.com/mariaalexissales/password-manager

/r/Python
https://redd.it/1hjjkrx
Looking for remote Django developer (contractor)

I'm looking for a Django Web Developer (backend and frontend) to work at SadServers as a contractor that can lead into a part-time or full-time role.

We use Bootstrap, Celery, REST API and Boto3 among other technologies, see our GitHub repo at [https://github.com/sadservers/sadservers](https://github.com/sadservers/sadservers) for details.

The main qualification is to have made significant code contributions to professional Django websites and be able to communicate well. Many things are a bonus, like having experience with our stack / Linux / AWS / SaaS.

There are no interviews with low signal questions like "why do you want to work for us?" or "what's your biggest weakness?", also no factoid technical questions that can be looked up quickly with a web search or an AI agent.

The process is straight-forward:

* Fill out this form: [https://docs.google.com/forms/d/1Y-ESW0rrlbh24B5vnbTamHN5w6toT-WIyipLPKTEIsY/](https://docs.google.com/forms/d/1Y-ESW0rrlbh24B5vnbTamHN5w6toT-WIyipLPKTEIsY/)
* If there's an initial good fit, we'll have one call to discuss what we need and for you to show us and talk about your work.
* If we are both happy, we'll send you an initial short real task to perform on our code and payment for it.

Thanks!

/r/django
https://redd.it/1hkb4x4
D Self-Promotion Thread

Please post your personal projects, startups, product placements, collaboration needs, blogs etc.

Please mention the payment and pricing requirements for products and services.

Please do not post link shorteners, link aggregator websites , or auto-subscribe links.

--

Any abuse of trust will lead to bans.

Encourage others who create new posts for questions to post here instead!

Thread will stay alive until next one so keep posting after the date in the title.

--

Meta: This is an experiment. If the community doesnt like this, we will cancel it. This is to encourage those in the community to promote their work by not spamming the main threads.

/r/MachineLearning
https://redd.it/1hjq0bm
Automated generation of categories for classification D

So I can use Bart zero-shot classification to quantify the relevance of an article to a predefined set of categories but I have a bunch of articles and I want to compute categories from them and then use those categories to classify lots of articles.

I thought maybe I could convert each article to a vector using a text embedding and then use an unsupervised learning algorithm to compute clusters of related articles and then project the groups back into text, maybe by recursively summarizing the articles in each group. However, I don't actually want the constraint that sets of categories must be disjoint which, I think, k-means would impose.

How else might this be accomplished?

/r/MachineLearning
https://redd.it/1hkc5d1
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/1hkb8wt
PipeFunc: Build Lightning-Fast Pipelines with Python - DAGs Made Easy

Hey r/Python!

I'm excited to share pipefunc (github.com/pipefunc/pipefunc), a Python library designed to make building and running complex computational workflows incredibly fast and easy. If you've ever dealt with intricate dependencies between functions, struggled with parallelization, or wished for a simpler way to create and manage DAG pipelines, pipefunc is here to help.

What My Project Does:

pipefunc empowers you to easily construct Directed Acyclic Graph (DAG) pipelines in Python. It handles:

1. Automatic Dependency Resolution: pipefunc intelligently determines the correct execution order of your functions, eliminating manual dependency management.
2. Lightning-Fast Execution: With minimal overhead (around 15 µs per function call), pipefunc ensures your pipelines run blazingly fast.
3. Effortless Parallelization: pipefunc automatically parallelizes independent tasks, whether on your local machine or a SLURM cluster. It supports any concurrent.futures.Executor!
4. Intuitive Visualization: Generate interactive graphs to visualize your pipeline's structure and understand data flow.
5. Simplified Parameter Sweeps: pipefunc's mapspec feature lets you easily define and run N-dimensional parameter sweeps, which is perfect for scientific computing, simulations, and hyperparameter tuning.
6. Resource Profiling: Gain insights into your pipeline's performance with detailed CPU, memory, and timing reports.
7. Caching: Avoid redundant computations with multiple caching backends.
8. Type Annotation Validation: Ensures type consistency across your pipeline to catch errors

/r/Python
https://redd.it/1hk85dp
Do you prefer react or svelte with your django app and why?

What are the pros and cons of both?

I want to build micro saas products for ideas I have. MVPs with the above mentioned technologies. My goal is to become a full stack dev eventually.

/r/django
https://redd.it/1hkgfkn
Python Youtube album downloader (Downloads video and splits it up into songs based on timestamps)

Purpose: Chrome fuckin sucks with memory so listening to music on YouTube uses so much ram. During exams, it gets kinda long and the amount by which it heats up gets me scared. BUTTTTT, Spotify is much better at playing music, so if only there was a way to listen to videos only on YouTube but on Spotify instead????? (there probably is but I couldn't find one that did it my way).

What My Project Does: A Python script that allows you to download an album from YouTube and split it up into songs, using a timestamps file as a reference. Note the "album" must be a YouTube video and not a playlist unfortunately :(

Target Audience: This is for anyone willing to use it. I kinda created it for myself but thought to post it here anyways

Comparison: Uses a lot of ffmpeg, so I guess that's the similar program? It's not exactly on par with any crazy video editing software but it does the job.

The only thing that kinda sucks is that the timestamps have to be in a certain format otherwise it wont work, I couldn't be asked/ couldn't think of a way to make a REGEX for it. But yh

/r/Python
https://redd.it/1hkazgu
AndroidSecretary - Your personal, context-aware AI SMS secretary for Android

Hello!

I just released a new project of mine, AndroidSecretary. It uses Flask for its backend, so Python was yet again of great use for this!

What My Project Does

This project provides you with an AI assistant that responds to your SMS messages contextually. It is customizable and can respond for you when you are not available.

Target Audience

Anyone with an Android device supported by the Automate app can have fun and utilize Android Secretary.

Also, this is not meant to be used by the average person. It is meant for developers to use for educational purposes only.

Comparison
So far, there are not many (if any) projects that do what AndroidSecretary does. For reference of features:

1. Ollama & OpenAI Support (with ollama, an external computer more powerful than the phone is likely needed to run more context-wise LLM's, unless you have a phone at least 12 GB of RAM)
2. Context-based assistant responses to messages received.
3. Customization:
1. Name your assistant
2. Limit the max amount of messages per hour per user
3. Blacklist and allowlist features (allowlist overrides blacklist)
4. Block spam feature (provided you give phone contact permissions to Automate)


/r/Python
https://redd.it/1hk6mjr