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
How to conditional in HTMX Partials ?

## How to conditional in HTMX Partials ?

/htmx/foo

 html
{% if request.user.is_superuser %}
<a>Admin Partials</a>
{% elif request.user.role == "role_a" %}
<a>A Partials</a>
{% elif request.user.role == "role_b" %}
<a>Admin Partials</a>
{% else %}
<a>Reguler Partials</a>
{% endif %}


/dashboard
 html
<div hx-get="/htmx/foo">
</div>



/r/django
https://redd.it/13oo5bz
Yay! I can officially join this subreddit now!

&#x200B;

Source Code:

https://preview.redd.it/hwvn9xrcvc1b1.png?width=1157&format=png&auto=webp&v=enabled&s=f62ff30e00038982b4a14bce89771672c3c40a53

Source code:

print("Hello World")

Thanks to the resources provided by the community (all of you), you have made it easy for me to start my programming journey.

/r/Python
https://redd.it/13omgv8
Flask and WebSocket - Real-Time Message exchange

Just wanted to share the first "real" (apart from the tutorials) project that I have created using Flask and using WebSocket (thru Flask-SocketIO).

I transformed my Raspberry Pi into a local "IoT hub" where I am reading several sensors and displaying them in real-time thru a Flask Web Application. I am receiving sensor readings every second and display them using the web application I created.

I am surprised by how easy it is to use WebSocket in Flask.

&#x200B;

Real-Time Temperature\/Humidity Dashboard using Python, Flask, and Flask-SocketIO

I have never used Bootstrap in an actual project but tried exploring it here and I think I like the outcome.

Maybe you are interested in looking.

Code: https://github.com/donskytech/dht22-weather-station-python-flask-socketio-multiple-sensors

/r/flask
https://redd.it/13ootfw
Show certain navbar options if user is logged in.

I am trying to have the navbar on my app show Home and Logout if the user is logged in and Home, Login and sign-up if the user is not.

Here is my current code:

<div class="navbar-nav">
{% if current_user.is_authenticated %}
<a class="nav-item nav-link" id="home" href="/">Home</a>
<a class="nav-item nav-link" id="logout" href="/logout">Logout</a>
{% else %}
<a class="nav-item nav-link" id="home" href="/">Home</a>
<a class="nav-item nav-link" id="login" href="/login">Login</a>
<a class="nav-item nav-link" id="signup" href="/signup">Sing-up</a>
{% endif %}
</div>

It currently shows Home/Login/Sign-up if you are not logged (which is what i want), but when you are logged in it still shows the same.

/r/flask
https://redd.it/13ktva7
Routes in Flask

Hello, I'm a beginner to Flask, and am trying to build an app, using a React frontend and a Flask backend. I'm having a little difficulty figuring out how to structure my app. If I have a button, and I want to make a call to my API on click, would I create a separate route for that button, or would it use the same route as that entire page, with a specified GET request?

Thank you for the help

/r/flask
https://redd.it/13kisfa
Trouble with user registration

I'm new to Django and Django rest framework. I'm following a tutorial/guide that is React frontend, django backend, and with redux as well. I've come across a problem is that when I'm registering a new user, I get an error telling me that the new user I'm trying to create already has an email that exist (which isn't true). However, that user still does get successfully registered, but I don't get automatically logged in with that new user.

Github repository: https://github.com/ngc918/dr-ecommerce

Stack overflow post: https://stackoverflow.com/questions/76302475/react-django-user-register-gives-me-400-bad-request/76303168#76303168

/r/djangolearning
https://redd.it/13otsxo
How run a daily scraper with Django?

I'd like to set up an application where users input a URL (or multiple URLs), and then once per day my application scrapes that URL. I was wondering how that setup might look, because I've done scraping before, and I've made Django apps, but never tried to make a scraper that lives in a Django app. Thanks for any tips!

/r/django
https://redd.it/13osnul
File path methods not working

Hello all,

currently experiencing issues importing data. Ive already tried/ read numerous S.O suggestions and none seem to work

File path: "C:\\Users\\marvi\\OneDrive\\Desktop\\MR WOLF\\MR_WOLF_DUMMY_DATA.csv"

import csv
import os
import matplotlib.pyplot as plt
import numpy as np
from sklearn.modelselection import traintestsplit
from sklearn.linear
model import LogisticRegression
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
from sklearn.metrics import meansquarederror
from sklearn.modelselection import crossvalscore
from sklearn.metrics import classification
report, confusionmatrix
from sklearn import preprocessing
from math import sqrt
import pandas as pd


**READ DATA**

data = open(r"C:\Users\marvi\OneDrive\Desktop\MR WOLF\MR
WOLFDUMMYDATA.csv")
data = pd.readcsv(path)
data.dtypes

which in turn returns

---------------------------------------------------------------------------

FileNotFoundError Traceback (most recent call last)

<ipython-input-7-a0d52672e39f> in <cell line: 1>()
----> 1 data = open(r"C:\Users\marvi\OneDrive\Desktop\MR WOLF\MR
WOLFDUMMYDATA.csv")


/r/JupyterNotebooks
https://redd.it/13ortum
Basic html not rendering

Hi I'm trying to learn flask and I have to admit it's not going well, I'm stuck on the very first thing, for some reason I can't get render template to work. What can I possibly be doing wrong?

from flask import Flask, redirect, url_for, render_template

app = Flask(__name__)

@app.route("/")
def index():
return render_template("index.html")

if __name__ == "__main__":
app.run(debug=True)

html is in templates folder as index.html and simply looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Page</title>
</head>
<body>
<h1>Home Page</h1>
<p>Hello!</p>
</body>
</html>

As basic as you can get, but it just returns a blank screen. So

/r/flask
https://redd.it/13p54iw
Tuesday Daily Thread: Advanced questions

Have some burning questions on advanced Python topics? Use this thread to ask more advanced questions related to Python.

If your question is a beginner question we hold a beginner Daily Thread tomorrow (Wednesday) where you can ask any question! We may remove questions here and ask you to resubmit tomorrow.

This thread may be fairly low volume in replies, if you don't receive a response we recommend looking at r/LearnPython or joining the Python Discord server at https://discord.gg/python where you stand a better chance of receiving a response.

/r/Python
https://redd.it/13p7vlm
Deploying a flask app to Heroku - timeout due to webscraping

Hi! (Just to preface, i'm a complete beginner with coding and deploying to heroku.)

Im attempting to deploy a python flask app which uses web scraping to gather words from the news. Im using serpapi for the web scraping and Redis to store on a database after the initial loading of the page. The problem is I can't get past the initial load because Heroku is giving me a timeout error.

specifically:

2023-05-22T18:12:58.846289+00:00 heroku[router\]: at=error code=H12desc="Request timeout" method=GET path="/" host=my-app-name.herokuapp.com request_id=d52dd5be-626a-43c0-bd01-1544f32c9bb1 fwd="86.16.228.212" dyno=web.1 connect=0ms service=30000ms status=503 bytes=0 protocol=https

I tried adding a timeout to my Procfile: web: gunicorn app:app --timeout 240

But nothing changed and im still getting the timeout error. I tried troubleshooting with GPT and it suggested using celery. Is this my only option? Any other suggestions are welcome!! When running locally, the webscraping usually on initial load takes a couple of minutes (max) as it is searching the first 100 results of google news and also performing sentiment analysis on the words.

I also posted this to r/heroku but thought to also post it here as its a larger community. Again, im a total beginner and this is my first project, so please go easy if this is an obvious fix or if

/r/flask
https://redd.it/13ozx9o
Django/DRF Custom Permission

I have a project with three kinds of user roles - Role A, Role B and Role C. I want to customize my Django admin such that;

Role A users can view and add Role B and Role C users,

Role B can view and add Role C users only(they cannot view, modify or Add Role A users)

Role C users can only view their personal accounts.

Is this possible? If yes how do you propose I go about achieving this? Every advice is much appreciated.

/r/django
https://redd.it/13p12n5
Question about wildcard URL in urls.py

So my app allows users to have personalized pages, e.g. https://mysite.com/username.

However, my site obviously also has other pages, like /dashboard, /settings, /login, /signup, etc.

The user should not be able to pick a username that's a hardcoded path in my urls.py.

What's best practice/the most elegant way to enforce prohibited usernames?

(I know I can just manually maintain a list and check against it anytime the user creates/updates his username, but I was wondering if there was a more elegant way to just check all paths in urls.py to prevent any clashes.)

/r/django
https://redd.it/13pdmbt
X-post from r/nginx : Flask app search results page needs to be reloaded to display results when served by nginx

I originally posted more or less this same question here, and although several people helped, we weren't able to find a solution.

I have set up a flask-based site that takes user input and makes a query to a postgres database. It works great when I run the app locally, but when I take it live on my vps, the search results in an error page. Except that if I hit reload (sometimes takes a few times), the results load as expected. Sometimes I have to hit reload a few times.



I suspect it might be related to nginx because if I just run the app and go directly on the vps with 'gunicorn --bind 0.0.0.0:5000' the app works as expected when I go to example.com:5000.


I found this in nginx error.log at the time of one of these failed searches:

2023/05/22 12:23:07 [warn] 994#994: *519 an upstream response is buffered to a temporary file /var/lib/nginx/tmp/proxy/2/00/0000000002 while reading upstream, client: 216.227.60.13, server: , request: "GET /us_news HTTP/1.1", upstream: "http://unix:/home/siteadmin/personal-website/siteapp.sock:/us_news", host: "example.com", referrer: "https://example.com/"



I found an error in my Flask app by turning on debugging. However I still need to figure out why this error would be fixed by simply reloading the page (why did

/r/flask
https://redd.it/13pepjv
Completely rebuilt classic Donkey Kong in Python using the PyGame module!

I made the entire first level of classic Donkey Kong in python (about 700+ lines of code) and used pygame so I could use sprites for the hammers/flames/player and barrels, and it came out really well!

I made a tutorial and showcase if anyone is curious:

https://www.youtube.com/watch?v=u6RV1lkHW8M

And all the code and assets are available here!

https://github.com/plemaster01/PythonDonkeyKong

/r/Python
https://redd.it/13p67zi
Filtered model through Proxy won't work

I've got the following model, but for some reason Iḿ unable to return a seperate proxy model with only the sales field = True. What am I overlooking?


class materials(models.Model):

sku = models.CharField(max_length=30)

name = models.CharField(max_length=200, blank=True)

description = models.TextField(blank=True)

plant = models.ForeignKey(plant, on_delete=models.CASCADE)

sales = models.BooleanField(default=False)

procured = models.BooleanField(default=False)

&#x200B;

def __str__(self):

return `self.name`

&#x200B;

class Meta:

verbose_name = 'Material'

verbose_name_plural = 'Materials'

&#x200B;

### Model manager to facilitate the proxy model for Sales Materials. ###

class salesmaterialsmngr(models.Manager):

def get_query_set(self):

return super(salesmaterialsmngr, self).get_query_set().filter(sales=True)

&#x200B;

### Model proxy to return Sales Materials only. ###

class sales_materials(materials):

objects: salesmaterialsmngr()

class Meta:

proxy=True

verbose_name = 'Sales Material'

verbose_name_plural = 'Sales Materials'

/r/djangolearning
https://redd.it/13p2fao
Where to host app?

Hi,

&#x200B;

I'm relatively new to Django and just hosted my first app using Digital Ocean's App Platform. It all works very well and I'm happy. However: I believe it's fairly expensive at $45,- a month for a basic project.

Does anyone have suggestions that are good for beginners but not as expensive?

/r/django
https://redd.it/13pjlc5
What's the most pointless program you've made with Python that you still use today?

As the title suggests. I've seen a lot of posts here about automations and as a result I've seen some amazing projects that would be very useful when it comes to saving time.

But that made me wonder about the opposite of this event. So I'm curious about what people have made that they didn't have to make, but they still use today.

I'll go first: I made a program to open my Microsoft Teams meetings when they've been scheduled to start. Literally everyone I've told about this has told me that it would be more sensible to just set an alarm. While I agree, I still can't help but smile when a new tab suddenly opens to a Microsoft Teams meeting while I'm distracted by something else.

So, what are those projects you've made that you didn't have to, but you still use for some reason or another.

/r/Python
https://redd.it/13pmej7