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
Flask Admin does not hash the User password

The code encrypts from the registration page but does not encrypt from Flask Admin. I have read examples online and written this code. I think the values for target, oldvalue and initiator are incorrect. I did not understand what they should be initialised with.


class User(db.Model, UserMixin):
__tablename__ = "user"
user_id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
firstname = db.Column(db.String(20), nullable=False)
lastname = db.Column(db.String(20), nullable=False)
email = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(80), nullable=False)
agreed_terms = db.Column(db.String(80), nullable=False)
reg_datetime = db.Column(db.DateTime, default=dt.now)
role = db.Column(db.String(20), nullable=False)

def __str__(self):
return self.username

@event.listens_for(User.password, 'set', retval=True)
def hash_user_password(target, password, oldvalue,

/r/flask
https://redd.it/1b57g1f
Append tags when creating a post with a many to many relationship in Flask

I want to add multiple tags to a new post at creation. The post and tag models are in a many to many relationship. I'm expecting the loop to create a tag then append it to the post. Is the 'NoneType' error coming from the routes code or the models code? Is there a different beginner friendly approach?

models.py

tags = sa.Table(
'tags',
db.metadata,
sa.Column('postid', sa.Integer, sa.ForeignKey('post.id'), primarykey=True),
sa.Column('tagid', sa.Integer, sa.ForeignKey('tag.id'), primarykey=True)
)
class Post(db.Model):
tablename = 'post'
id: so.Mappedint = so.mappedcolumn(primarykey=True)
body: so.Mappedstr = so.mappedcolumn(sa.Text)
timestamp: so.Mapped[datetime] = so.mapped
column(index=True, default=lambda: datetime.now(timezone.utc))
userid: so.Mapped[int] = so.mappedcolumn(sa.ForeignKey(User.id), index=True)
author: so.MappedUser = so.relationship(backpopulates='posts')
language: so.Mapped[Optional[str]] = so.mapped
column(sa.String(5), default='')


/r/flask
https://redd.it/1b51415
<!DOCTYPE html> over {% load x %}

The internet forgot to include this title.

Doctype has to be the very first line of an html document or "template", the {% load x %} templatetag occupies one line, they belong under the <!DOCTYPE html> line.

New users need to be able to find this in the internet. and this info is not anywhere else.


Great software! I finished learning it today as a hobbie! I finally know how to make websites.

Thank you.


/r/django
https://redd.it/1b5c4er
Django DebugToolbar not working in docker compose

Only came across this article that's addressing my probelm - https://blog.juanwolf.fr/posts/programming/2017-08-26-django-debug-toolbar-not-showing-docker-compose/

&#x200B;

But how do i continue to develop using docker compose and get debugToolbar to work? I wonder if any of you have dealt with this annoyance before. It works great when i run locally.

&#x200B;

So far, the compromise i found is...run django locally and then run the rest of the services (db, redis etc) via the compose file but would ideally like to develop within docker-compose since i have everything mounted and can see code changes instantly...just debugtoolbar not liking docker network setup... thanks

/r/django
https://redd.it/1b52zmd
Can't Resolve Unintended "Id" and "Business" Fields in Django Formset



Hey Django Community,

I'm in a bind with a Django formset that's rendering extra labels "Id:" and "Business:" which aren't supposed to be there. I've already tried excluding these fields explicitly in my CreditCardFormSet
but to no avail. Here's a brief rundown of the situation:


CreditCardFormSet = inlineformset_factory(

BusinessDetail, CreditCard,

fields=('card_type', 'last_8_digits'),

extra=3, max_num=3,

can_delete=False,

exclude=('business', 'id',) # Tried excluding here

)

{% for form in formset %}

<div class="form-control w-full">

{% for field in form %}

<label>{{ field.label }}:</label>

{{ field }}

{% endfor %}

</div>

{% endfor %}


To debug, I printed out the fields of the first form in the formset, and to the dict output included both 'id' and 'business' keys, which I hadn't defined in my formset fields:


print(formset.forms[0\].fields) # Output: dict_keys(['card_type', 'last_8_digits', 'id', 'business'\])




my CreditCardFormset doesn't define 'id' or 'business' as fields, yet they're showing up.

/r/django
https://redd.it/1b5dypr
I hate typing out every 'self.x = x' line in an init method. Is this alternative acceptable?

class Movable:
def init(self, x, y, dx, dy, worldwidth, worldheight):
"""automatically sets the given arguments. Can be reused with any class that has an order of named args."""

nonmembers = #populate with names that should not become members and will be used later. In many simple classes, this can be left empty.

for key, value in list(locals().items())1:: #exclude 'self', which is the first entry.
if not key in nonmembers:
setattr(self, key, value)

#handle all nonmembers and assign other members:

return

I always hate how redundant and bothersome it is to type "self.member = member" 10+ times, and this code does work the way I want it to. It's

/r/Python
https://redd.it/1b5bc8g
shavis - Visualize SHA256 and SHA1

https://github.com/kernel137/shavis
Install with

pip install shavis
shavis is (secure hash algorithm visualization), is a CLI tool that can hash any file (Only through SHA256) and create an 8x8 pixel image displaying the hash through themed colours.


What My Project Does:

Main functionality of this CLI tool is taking the 64 digit hex number (SHA256 hash) and, through 16 hex colors in ascending order, turning it into a 8x8 pixel image that can then be scaled to powers of two.
Shavis also supports piping: echo -n "Hello World!" | shavis

This also works for git hashes, since git hashes are SHA1, images for this hash are 8x5, I think with some clever integration, its possible to integrate a small res picture of a git commit hash to quickly visualize the hash within vscode or some other platform.
A quick way to get a visual of the last git commit while within a local git repository is:

git rev-parse HEAD | shavis -g

What do you guys think? Is it a worthwhile investment to implement other hashes? Is it an interesting project? Do you guys have any ideas about what to add to it?


/r/Python
https://redd.it/1b5em7s
Automatic wallpaper changer - Wallpapertime

Hello everyone, I decided to write a small program on python that allows you to change the wallpaper by setting them a time interval.

Github: https://github.com/Niamorro/Wallpapertime

# What My Project Does:

WallpaperTime is a versatile Python application designed to dynamically change your wallpaper based on specified time intervals.

# Target Audience:

for those who need the functionality of this program

##Comparison:
WallpaperTime stands out with its focus on time-based intervals for wallpaper changes. Here's how it differs from existing alternatives:

# Time-Driven Wallpaper Changes:

WallpaperTime distinguishes itself by allowing users to set specific time intervals for wallpaper changes

# System Tray Integration:

The application seamlessly integrates with the system tray.

# Autostart and Minimize Options:

WallpaperTime offers autostart and minimize options, ensuring a smooth and unobtrusive startup experience.

# Intuitive User Interface:

In summary, WallpaperTime brings a customization and user-friendly features, making it a standout choice for those who want to curate their desktop experience b
ased on time.

/r/Python
https://redd.it/1b5gsoh
MongoDb Aggregation Tutorial for complex Mongodb Queries

🚀 Calling all developers! 🚀
I have created this amazing Tutorial on MongoDb Aggregation ( link ) for writing complex queries. Do have a look on it and all feedbacks are appreciated. Like, share, and subscribe for more coding excellence! 🌐💻 #MongoDB #Aggregation #WittyCoder #CodeMasters #Programming #TechTalks #LearnToCode #HappyCoding 🔥

/r/Python
https://redd.it/1b5o4sa
sew: SQLite Extensions and Wrappers

https://github.com/icyveins7/sew

# Motivation

This project started because at work I realised I was copying / editing code to create tables / insert rows etc in many different scripts. Oftentimes the structure of the tables, and the way I inserted the data, was the same; just inserting all columns.

So at first I started auto-generating my CREATE TABLE and INSERT statements, but then it eventually grew into this.

# What This Project Does

The goal of this package is essentially to reduce the code typed for simple CRUD operations.

I pretty much only use this now because I can always dip down to make custom statements if I want to anyway (which still happens for more complex things like inner joins).

Here's an example:

Before:

import sqlite3 as sq
con = sq.connect("path/to/db")
cur = con.cursor()
cur.execute("select from mytable where ...")
results = cur.fetchall()

After:

import sew
db = sew.Database("path/to/db")
db['mytable'].select("
", ...)
results = db.fetchall()

# Target Audience

This is really for anyone who uses SQLite from python’s in built library.

Hopefully someone else will find this useful; it’s my first ever package uploaded to PyPI

/r/Python
https://redd.it/1b4mn60
Is there any way to deploy a Django website with image uploads for free?

I was wanting to do something like a social network project, it would be essential to allow image uploads. I was thinking about using vercel for the server and railway's postgre for the database (I have no idea if this will work for free). But I still needed a system to host images. Any suggestion? I didn't need a lot of storage, 500mb~1gb would be enough.

/r/django
https://redd.it/1b5uzwc
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/1b5wbuu
NameError: name 'rolesusers' is not defined

If I put the class 'Roles\
users' above the user table, I get the message, 'roles' is not defined. If I start with the user table, I get the error, 'roles_users' has not been defined. When I searched, I saw that the error can be corrected using '__table_args__ = {'extend_existing': True}'. I have done that. I dont know if I should have done it on both tables.

Could it be the PrimaryKeyConstraint?

2. I have a role and a user table. A user can be an employee or a customer. Is it necessary to create a many to many relationship?

&#x200B;

class Role(db.Model):
tablename = "role"
id = db.Column(db.Integer(), primarykey=True)
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))

class User(db.Model, UserMixin):
tablename = "user"
table
args = {'extendexisting': True}
id = db.Column(db.Integer, primary
key=True)
username = db.Column(db.String(20), unique=True, nullable=False)


/r/flask
https://redd.it/1b5gzul
Strange route behavior I'm getting has me confused

This is going to be difficult to explain but I have got to figure this out. So, as many have seen from my multiple posts of late, I am writing a flash card website. You create a deck, add flashcards, and then can study them.


So I have a manage deck button that opens up a grid of all of your decks, then you click on the deck and you see a list of all the flash cards you created for that deck.


one of the decks I happen to have I named D10. So when you are managing the deck the url is,
/managesingledeck/D10


Here is the html:

<div class="menu_grid">
{% for deck in user.decks %}
<div class="menu_buttons" onclick="location.href='/managesingledeck/{{deck.title}}' ">{{deck.title}}</div>
{% endfor %}
<div class="menu_buttons" onclick="location.href='/createDeck' ">Create New Kwik Deck</div>


/r/flask
https://redd.it/1b4wli7
A simplified way to get SQL data into DataFrames for analysis

I’ve been looking forward to sharing my first open-source Python project with you all!

Repo: https://github.com/JustinFrizzell/sqlconnect

Docs & Examples: https://sqlconnect.readthedocs.io/en/latest/index.html

# What My Project Does

SQLconnect simplifies getting data out of databases like Postgres, Microsoft SQL Server and Oracle. Pandas DataFrames can be directly populated from .sql files in as little as three lines of code. You can also populate SQL tables directly from DataFrames. Database connections are managed in a single config file, and sensitive credentials are kept separately in an environment variable file (kept away from version control). For a future update, I’d like to provide integration with secure credential management systems like Azure Key Vault and HashiCorp Vault.

# Target Audience

Data analysts who need a more convenient way to get data from SQL databases into Pandas DataFrames. SQLconnect helps you avoid re-writing all the same boilerplate code associated with reading SQL from a file and connecting to databases. Also, I’ve seen teammates accidently save database credentials in Python scripts and commit them to version control leading to security nightmares. SQLconnect helps keep your configuration separate from your code and greatly reduces the chance of accidently sharing database passwords.

# Comparison

SQLconnect is a thin wrapper around SQLAlchemy and Pandas, however it provides a way

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