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 get objects with certain foreignkey relationships in ORM?

Assume we have a product model:

`class Product(models.Model):`

`name = models.Charfield()`And a property model where possible properties are defined (like "price", "color", "weight"...):

`class Property(models.Model):`

`name = models.CharField()`

And we keep product properties in a separate model:

`class ProductProperty(models.Model):`

`propery = models.ForeignKey(Property)`

`product = models.ForeignKey(Product)`

`value = models.Charfield()`

I want to get product objects which have certain properties. For instance, **I want to get objects only if "price" and "color" is defined for them in ProductPropery table.**

I obtain the required properties as objects, but I could not solve how can I get products that have all of the given properties.

To rephrase, I'm looking for something like this:

`properties = Property.objects.filter(Q(name__contains="Price") | Q(name__contains="Color")) #this could return one or multiple property objects`

​

`products = properties.productproperty_set.product_set # imaginary line I made up to show what I want to get`

I could only think of: looping through properties and sub-loop for related ProductProperties to get their products and create multiple lists, and then create a list that's made of common elements (products that are included in each list)

It would be great if you could help,

Best wishes

/r/django
https://redd.it/ihhszo
How to get objects with certain foreignkey relationships in ORM?

Assume we have a product model:

`class Product(models.Model):`

`name = models.Charfield()`

And a property model where possible properties are defined (like "price", "color", "weight"...):

`class Property(models.Model):`

`name = models.CharField()`

And we keep product properties in a separate model:

`class ProductProperty(models.Model):`

`propery = models.ForeignKey(Property)`

`product = models.ForeignKey(Product)`

`value = models.Charfield()`

I want to get product objects which have certain properties. For instance, **I want to get objects only if "price" and "color" is defined for them in ProductPropery table.**

I obtain the required properties as objects, but I could not solve how can I get products that have all of the given properties.

To rephrase, I'm looking for something like this:

`properties = Property.objects.filter(Q(name__contains="Price") | Q(name__contains="Color")) #this could return one or multiple property objects`

​

`products = properties.productproperty_set.product_set # imaginary line I made up to show what I want to get`

I could only think of: looping through properties and sub-loop for related ProductProperties to get their products and create multiple lists, and then create a list that's made of common elements (products that are included in each list)

It would be great if you could help,

Best wishes

/r/django
https://redd.it/ihisa1
Way to loop np.save or np.savetxt?

I have very large data sets and so need to save by appending parts. The simplified version is below and I’m not sure why it doesn't work:

number = 10 #the number of iterations
thing = np.array(1,2,3)

f = open('a.npy', 'ab') #open a file for appending
for i in range(number):
np.save(f, thing) #save the thing to a file

with open('a.npy', 'rb') as f: #open a file for reading
a = np.load(f)
print(a) #this just returns 1,2,3 (not this ten times which is what I want).


I.e. I want to return [1,2,3,1,2,3,1,2,3,...,1,2,3]

/r/Python
https://redd.it/mpxahi
Image object being created on local host but not on heroku? whats going wrong?

here is the view:

def img_upload(request,case_id):
#this is only to add photos
if request.method == "POST":
case = Case.objects.get(id=case_id)
if (case.author == request.user) and (Image.objects.filter(Case=case).count() < 3):
# print("less than 3 and case author")
my_file = request.FILES.get("file")
Image.objects.create(photo=my_file,Case_id=case_id)
messages.success(request, 'Added Image')
else:
messages.error(request, "You can't add more than 3 images")

return HttpResponse(".")


/r/django
https://redd.it/ped73x
How to Create An Twitterbot with simpletwitter

Github Repository: [https://github.com/pravee42/simpletwitter](https://github.com/pravee42/simpletwitter)

```
from simpletwitter import SimpleTwitter

email = "Twitter_User_Email_Address"
password = "Twitter_Password"
user_name = "Abipravi1"
#here i have entered my twitter username but you need to enter your's in this case

no_of_tweets = 10 #this value is necessary how many no of tweets you want to perform operation

bot = SimpleTwitter(email, password, no_of_tweets, user_name)
#Creating Instance

hashtags = ['#abipravi', #pythonmodule', '#twitter_bot']
tweetmessage = "My first tweet by simple twitter"
bot.login() # to login into the account

bot.like_tweet(hashtags) # like the tweet

bot.unlike_liked_tweets(5) # unlike the liked tweet

bot.tweet(tweetmessage) # put some tweet



/r/Python
https://redd.it/r7mtzy
Help with UpdateView and getting key:value from ModelForm

views.py

def WantListUpdateView(request, pk, username=None):
context = {}

def getusername(self):
username = self.request.user.username
context['data'] = {'username' : username}

initial
data = CoinWantlist.objects.get(pk=pk) #This works
initialdata = initialdata.meta.getfields() #HERE IS WHERE I NEED HELP, how do I get the key : value passed into context.

return render (request, 'wantlist/wantlist.html', context)

I'm trying to make an update view that prefills the form data into the form for the user to update. The URL works but I need help getting the KEY : VALUE passed into context to create the initial data.

I'm sure this is a simple .something.get.something that I just haven't been able to find yet.

/r/django
https://redd.it/rurzz9
PyUpdater is no longer maintained. What now? - Tufup: automated updates for stand-alone Python applications.

Hello world! I want to recommend a wonderful open-source package called **Tufup.** It's a simple software updater for stand-alone Python *applications*. This package was created as a replacement for **PyUpdater**, given the fact that [PyUpdater has been archived and is no longer maintained](https://github.com/Digital-Sapphire/PyUpdater#this-is-the-end). However, whereas **PyUpdater** implements a *custom* security mechanism to ensure authenticity (and integrity) of downloaded update files, **Tufup** is built on top of the security mechanisms implemented in the [python-tuf](https://github.com/theupdateframework/python-tuf) package, a.k.a. **TUF** (The Update Framework). By entrusting the design of security measures to security professionals, **Tufup** can focus on high-level tools.

Do note that, although **Tufup** offers the same basic functionality as **PyUpdater**, there are some differences:

* **Tufup** uses [python-tuf](https://github.com/theupdateframework/python-tuf) to secure the update process. This means you'll need to understand a little bit about the principles behind [TUF](https://theupdateframework.io/overview/). You can tailor the level of security to your needs, from highly secure, to slightly secure.
* **PyUpdater** was tightly integrated with [PyInstaller](https://pyinstaller.org/en/stable/), but **Tufup** is not. You *can* use **Tufup** with **PyInstaller**, as illustrated in the [tufup-example](https://github.com/dennisvang/tufup-example), but it is not required. You can also use it with any other packaging method, or you can even distribute a plain python script or just any directory of files.
*

/r/Python
https://redd.it/xsu2tn
Trying to build a dynamic Table using Flask/turbo/threading

Hey guys

Im currently trying to create a dynamicly updating table, housing some data and I'm slowly loosing it.

The problem is, no matter what I do, I can't seem to get it to consistently update.

The wierd thing is, sometimes it will randomly work,but it will start duplicating the "delete all" button with every update. And then after a quick reload of the side, without changing anything in the code, it won't update anymore.

I also sometimes get a "GET /turbo-stream HTTP/1.1" 500 -" error, and then without changing anything, just restarting frontend.py, it won't appear again.

The following code is what I have currently:

frontend.py:

import threading
import time

from flask import Flask, Response, render_template, url_for
from turbo_flask import Turbo

from Backend import Backend

app = Flask(__name__)
turbo = Turbo(app)
app.config['SERVER_NAME'] = '192.168.2.183:5000'

#This is what trap_data looks like (for a single entry):
#(141, '192.168.1.1', 'Authentication Failure', 'Invalid username or password', 3, 1,

/r/flask
https://redd.it/10dw2xv
Little confused how how data is passed from Python up to html

As many have probably seen from my incessant posts as of late, I have been writing a flashcard website. My starting point was a tutorial to write basic notes using a sqlalchemy and I've been fiddling around getting it to do what I want. One thing that confuses me is exactly how the html side is seeing all my database entries. So In python I have,


fetchedflash = Flashcard()
@views.route('/', methods = ["GET", "POST"]) #this is homepage route(url)
@loginrequired
def home():
...

return rendertemplate("home.html", user = currentuser...

Where current_user(something from flask_login I also don't fully understand yet) points to my user entry in the database. The User entry is tied to decks and flashcards also in the database entry.


The html has,

 {% for deck in user.decks %}
...


And I'm really confused as to how the HTML is seeing all the deck elements in "user." IS the entire user database being

/r/flask
https://redd.it/1avpsge
How do I add a new entry to my many to many related table in Django?

I have two models Course and Educators. Course has 3 fields course\_name, course\_educators and course\_past\_educators which link Educators to Courses by many to many. I want to write a function so that whenever a new entry is added to course\_educators that entry will be copied over to course\_past\_educators.

#models.py
#code for Educators model
class Educators(models.Model):
educator_name=models.CharField(max_length=20,default=None)
educator_img = models.ImageField(upload_to='educators_img',default=None)

#code for Courses model
class Course(models.Model):
course_name = models.CharField(max_length=100)
course_educators=models.ManyToManyField(Educators, related_name='current_educators', default=None, blank=True)
course_past_educators=models.ManyToManyField(Educators, related_name='past_educators', default=None, blank=True)

#views.py
#This is the function I wrote so that entries into course_past_educators are automatically added when course_educators is added with another entry.
u/receiver(m2m_changed, sender=Course.course_educators.through)
def create_past_educator_on_add(sender, instance, action, reverse, model, pk_set, **kwargs):
if action == 'post_add' and reverse is False:


/r/djangolearning
https://redd.it/1cq2j42
CSRF Token Error

Hey I get this CSRF Token Error on my webserver.
i dont get where this is coming from because they are the same token before and after.
I checked my steinngs and my conf and cant find the error.


https://preview.redd.it/ar4qu70h4ste1.png?width=1222&format=png&auto=webp&s=28e79c8dc2338487301ac0a1fd642096dbe7097d

https://preview.redd.it/nkco18wj4ste1.png?width=1210&format=png&auto=webp&s=0d2ba8ec728bac99aad92f52527fd353ba6cb815

#This is my settigs for nginx

    SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
    SECURE_SSL_REDIRECT = True
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True

    # Security headers
    SECURE_CONTENT_TYPE_NOSNIFF = True
    SECURE_BROWSER_XSS_FILTER = True
    X_FRAME_OPTIONS = "DENY"

    # HSTS settings
    SECURE_HSTS_SECONDS = 31536000  # 1 year
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_PRELOAD = True
    SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
    SECURE_SSL_REDIRECT = True
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True


/r/djangolearning
https://redd.it/1jv1s9a
db.init_app(app) Errror

Hi I am a compleat Noob (in flask), i have an Error in my Program that says: TypeError: SQLAlchemy.init\_app() missing 1 required positional argument: 'app' and i dont know what is wrong ):


This is the code pls Help me:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path

db = SQLAlchemy
DB_NAME = "database.db"

def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'hjshjhdjah kjshkjdhjs'
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    db.init_app(app) #this thing makes the problem

    from .views import views #thies are just website things
    from .auth import auth

    app.register_blueprint(views, url_prefix='/')
    app.register_blueprint(auth, url_prefix='/')

    from .models import User, Note #that are moduls for the data base

    with app.app_context():


/r/flask
https://redd.it/1kmg69c
Having trouble writing to .txt and CSV files while Flask is running.

So I am trying to write simple submission form text from a website to a text file. The form submits fine and I can even print out my data, but it won't write to a text or csv file for some reason. No errors, the file is just empty. I run the same snippit of code in another file that isn't running flask and the code works fine. It writes to the text file. I can even print out the form text and see it in the debug console; but it just won't write to a file. I feel like I'm in the twilight zone.

#this function should work, but it does'nt
def writetotext(data):
with open('DataBase.txt',mode='a') as database:
email=data'email'
subject=data'subject'
message=data'message'
print(f'\n{email},{subject},{message}')
file=database.write(f'\n{email},{subject},{message}')



/r/flask
https://redd.it/1on2o1l