Serializing a dictionary that is not a model in Django restframework
I have read a few answers and posts about serializing an dictionary . But I still can't get it to work. Here is the problem. I do some data processing in django app , and it returns this dictionary (It has information about a quiz):
{101: {'subject': 'General-Intelligence', 'topics': ['Coding Decoding', 'Dice & Boxes', 'Statement & Conclusion', 'Venn Diagram', 'Mirror and Water Image', 'Paper Cutting and Folding', 'Clock/Time', 'Matrix', 'Direction', 'Blood Relation', 'Series Test', 'Ranking', 'Mathematical Operations', 'Alphabet Test', 'Odd one out', 'Analogy'], 'num_questions': 25, 'creator': 'Rajesh K Swami'}}
I want to serialize this dictionary. So what I have done is created a class for this dictionary. ie.
class PsudoTests:
def __init__(self,body):
self.body = body
Also a serializer:
class PsudoTestSerializer(serializers.Serializer):
body = serializers.DictField()
Now in api view :
class TestListView(generics.ListAPIView):
def get_serializer_class(self):
serializer = PsudoTestSerializer
def get_queryset(self):
me = Studs(self.request.user)
tests = me.toTake_Tests(1) # this method brings in the above dictionary that i want to serialize
p_test = PsudoTests(tests) #this creates an instance of class created above
return p_test
Now when i go to the url there is a key error:
"Got KeyError when attempting to get a value for field body on serializer PsudoTestSerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the dict instance.\nOriginal exception text was: 'body'."
/r/django
https://redd.it/8apaxg
I have read a few answers and posts about serializing an dictionary . But I still can't get it to work. Here is the problem. I do some data processing in django app , and it returns this dictionary (It has information about a quiz):
{101: {'subject': 'General-Intelligence', 'topics': ['Coding Decoding', 'Dice & Boxes', 'Statement & Conclusion', 'Venn Diagram', 'Mirror and Water Image', 'Paper Cutting and Folding', 'Clock/Time', 'Matrix', 'Direction', 'Blood Relation', 'Series Test', 'Ranking', 'Mathematical Operations', 'Alphabet Test', 'Odd one out', 'Analogy'], 'num_questions': 25, 'creator': 'Rajesh K Swami'}}
I want to serialize this dictionary. So what I have done is created a class for this dictionary. ie.
class PsudoTests:
def __init__(self,body):
self.body = body
Also a serializer:
class PsudoTestSerializer(serializers.Serializer):
body = serializers.DictField()
Now in api view :
class TestListView(generics.ListAPIView):
def get_serializer_class(self):
serializer = PsudoTestSerializer
def get_queryset(self):
me = Studs(self.request.user)
tests = me.toTake_Tests(1) # this method brings in the above dictionary that i want to serialize
p_test = PsudoTests(tests) #this creates an instance of class created above
return p_test
Now when i go to the url there is a key error:
"Got KeyError when attempting to get a value for field body on serializer PsudoTestSerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the dict instance.\nOriginal exception text was: 'body'."
/r/django
https://redd.it/8apaxg
reddit
Serializing a dictionary that is not a model in Django... • r/django
I have read a few answers and posts about serializing an dictionary . But I still can't get it to work. Here is the problem. I do some data...
Super Beginner Python question.
Hi all,
I am currently programming some descriptive analytics on a CSV file.
I have imported using Pandas as far as I know.
My general aim; Create a bar chart of Location occurrence within the CSV file
The image below is as far as I have got but this is not all of the variables.
I am wondering if there is a way of importing the 'many' different locations as separate variables as I need to add 1 to each variable when the regex is matched against the CSV.
The CSV column is called; \(Some are abbreviated for ease as variables\)
**Borough**
>COL = 0
>
>Barnet = 0
>
>Bexley = 0
>
>BAD = 0
>
>Brent = 0
>
>Bromley = 0
>
>Camden = 0
>
>Croydon = 0
>
>Ealing = 0
>
>Enfield = 0
>
>Greenwich = 0
>
>Hackney = 0
>
>HAF = 0
>
>Haringey = 0
>
>Harrow = 0
>
>Havering = 0
>
>Hillingdon = 0
>
>Hounslow = 0
>
>Islington = 0
>
>KAC = 0
>
>KUT = 0
>
>Lambeth = 0
>
>Lewisham = 0
>
>Merton = 0
>
>Newham = 0
>
>Redbridge = 0
>
>RUT = 0
>
>Southwark = 0
>
>Sutton = 0
>
>TowerHamlets = 0
>
>WalthamForest = 0
>
>Wandsworth = 0
>
>Westminster = 0
>
>OuterBorough = 0
>
>InnerBorough = 0
Here is my current code with the output of the image below:
#Start of Imports
import csv
import sys
import numpy as np
import pandas as pd
import re
import matplotlib.pyplot as plt
#End of Imports
#Start of Declarations
COL = 0
Barnet = 0
Bexley = 0
BAD = 0
Brent = 0
Bromley = 0
Camden = 0
Croydon = 0
Ealing = 0
#This is as far as I got when I thought something was wrong?
Enfield = 0
Greenwich = 0
Hackney = 0
HAF = 0
Haringey = 0
Harrow = 0
Havering = 0
Hillingdon = 0
Hounslow = 0
Islington = 0
KAC = 0
KUT = 0
Lambeth = 0
Lewisham = 0
Merton = 0
Newham = 0
Redbridge = 0
RUT = 0
Southwark = 0
Sutton = 0
TowerHamlets = 0
WalthamForest = 0
Wandsworth = 0
Westminster = 0
OuterBorough = 0
InnerBorough = 0
#End of Declarations
#Starts reading 'csv file'
csv = pd.read_csv ('land-area-population-density-london.csv') #Not sure what this does, index_col=3)
#Start of IF Statement
csva = np.array(csv)
for column in np.arange(0, csva.shape[0]):
if re.match(r"Barnet", str(csva[column][2])) is not None:
Barnet = Barnet + 1
elif re.match(r"Bexley", str(csva[column][2])) is not None:
Bexley = Bexley + 1
elif re.match(r"City of London", str(csva[column][2])) is not None:
COL = COL + 1
elif re.match(r"Barking and Dagenham", str(csva[column][2])) is not None:
BAD = BAD + 1
elif re.match(r"Brent", str(csva[column][2])) is not None:
Brent = Brent + 1
elif re.match(r"Bromley", str(csva[column][2])) is not None:
Bromley = Bromley + 1
elif re.match(r"Camden", str(csva[column][2])) is not None:
Camden = Camden + 1
elif re.match(r"Croydon", str(csva[column][2])) is not None:
Croydon = Croydon + 1
elif re.match(r"Ealing", str(csva[column][2])) is not None:
Ealing = Ealing + 1
#End of IF Statement
#Start of graph fields
#Below: Places is the labels for the placesvar
places = ('Barnet', 'Bexley', 'City of London', 'Barking and Dagenham', 'Brent', 'Bromley', 'Camden', 'Croydon', 'Ealing')
#Below: placesvar the actual 'places' pulled from CSV
placesvar = [Barnet, Bexley, COL, BAD, Brent, Bromley, Camden, Croydon, Ealing]
#Y Positioning numpy.arange (Again no idea what this does) length 'places pulled from csv'
y_pos = np.arange(len(placesvar))
#End of graph fields
#Start of Graph positions and Names
plt.bar(y_pos, placesvar, align='center')
plt.xticks(y_pos, places, rot
Hi all,
I am currently programming some descriptive analytics on a CSV file.
I have imported using Pandas as far as I know.
My general aim; Create a bar chart of Location occurrence within the CSV file
The image below is as far as I have got but this is not all of the variables.
I am wondering if there is a way of importing the 'many' different locations as separate variables as I need to add 1 to each variable when the regex is matched against the CSV.
The CSV column is called; \(Some are abbreviated for ease as variables\)
**Borough**
>COL = 0
>
>Barnet = 0
>
>Bexley = 0
>
>BAD = 0
>
>Brent = 0
>
>Bromley = 0
>
>Camden = 0
>
>Croydon = 0
>
>Ealing = 0
>
>Enfield = 0
>
>Greenwich = 0
>
>Hackney = 0
>
>HAF = 0
>
>Haringey = 0
>
>Harrow = 0
>
>Havering = 0
>
>Hillingdon = 0
>
>Hounslow = 0
>
>Islington = 0
>
>KAC = 0
>
>KUT = 0
>
>Lambeth = 0
>
>Lewisham = 0
>
>Merton = 0
>
>Newham = 0
>
>Redbridge = 0
>
>RUT = 0
>
>Southwark = 0
>
>Sutton = 0
>
>TowerHamlets = 0
>
>WalthamForest = 0
>
>Wandsworth = 0
>
>Westminster = 0
>
>OuterBorough = 0
>
>InnerBorough = 0
Here is my current code with the output of the image below:
#Start of Imports
import csv
import sys
import numpy as np
import pandas as pd
import re
import matplotlib.pyplot as plt
#End of Imports
#Start of Declarations
COL = 0
Barnet = 0
Bexley = 0
BAD = 0
Brent = 0
Bromley = 0
Camden = 0
Croydon = 0
Ealing = 0
#This is as far as I got when I thought something was wrong?
Enfield = 0
Greenwich = 0
Hackney = 0
HAF = 0
Haringey = 0
Harrow = 0
Havering = 0
Hillingdon = 0
Hounslow = 0
Islington = 0
KAC = 0
KUT = 0
Lambeth = 0
Lewisham = 0
Merton = 0
Newham = 0
Redbridge = 0
RUT = 0
Southwark = 0
Sutton = 0
TowerHamlets = 0
WalthamForest = 0
Wandsworth = 0
Westminster = 0
OuterBorough = 0
InnerBorough = 0
#End of Declarations
#Starts reading 'csv file'
csv = pd.read_csv ('land-area-population-density-london.csv') #Not sure what this does, index_col=3)
#Start of IF Statement
csva = np.array(csv)
for column in np.arange(0, csva.shape[0]):
if re.match(r"Barnet", str(csva[column][2])) is not None:
Barnet = Barnet + 1
elif re.match(r"Bexley", str(csva[column][2])) is not None:
Bexley = Bexley + 1
elif re.match(r"City of London", str(csva[column][2])) is not None:
COL = COL + 1
elif re.match(r"Barking and Dagenham", str(csva[column][2])) is not None:
BAD = BAD + 1
elif re.match(r"Brent", str(csva[column][2])) is not None:
Brent = Brent + 1
elif re.match(r"Bromley", str(csva[column][2])) is not None:
Bromley = Bromley + 1
elif re.match(r"Camden", str(csva[column][2])) is not None:
Camden = Camden + 1
elif re.match(r"Croydon", str(csva[column][2])) is not None:
Croydon = Croydon + 1
elif re.match(r"Ealing", str(csva[column][2])) is not None:
Ealing = Ealing + 1
#End of IF Statement
#Start of graph fields
#Below: Places is the labels for the placesvar
places = ('Barnet', 'Bexley', 'City of London', 'Barking and Dagenham', 'Brent', 'Bromley', 'Camden', 'Croydon', 'Ealing')
#Below: placesvar the actual 'places' pulled from CSV
placesvar = [Barnet, Bexley, COL, BAD, Brent, Bromley, Camden, Croydon, Ealing]
#Y Positioning numpy.arange (Again no idea what this does) length 'places pulled from csv'
y_pos = np.arange(len(placesvar))
#End of graph fields
#Start of Graph positions and Names
plt.bar(y_pos, placesvar, align='center')
plt.xticks(y_pos, places, rot
Flask-Admin SelectField Choices, not a valid option.
Hey, I got dynamic choices (selectfield choices depending on previous selectfield's data) working visually, but the problem seems to be, that the choices do not get updated in back end, and so it throws a validation error if I do not select from the original, hard coded selection.
Here is the ModelView example:
def scaffold_form(self):
form_class = super(TeacherTaskView, self).scaffold_form()
sport_choices = Sport.query.filter_by(type='')
form_class.sport2 = SelectField('Sport', choices=[(sport.id, sport.sport) for sport in sport_choices.all()], coerce=int)
#This is the hard coded first example choices
form_class.type = SelectField('Type', choices=[(int(type.id), type.type) for type in Sport.query.filter_by(sport='Kergejõustik').all()], coerce=int)
return form_class
def on_model_change(self, form, model, is_created):
/r/flask
https://redd.it/akfx0j
Hey, I got dynamic choices (selectfield choices depending on previous selectfield's data) working visually, but the problem seems to be, that the choices do not get updated in back end, and so it throws a validation error if I do not select from the original, hard coded selection.
Here is the ModelView example:
def scaffold_form(self):
form_class = super(TeacherTaskView, self).scaffold_form()
sport_choices = Sport.query.filter_by(type='')
form_class.sport2 = SelectField('Sport', choices=[(sport.id, sport.sport) for sport in sport_choices.all()], coerce=int)
#This is the hard coded first example choices
form_class.type = SelectField('Type', choices=[(int(type.id), type.type) for type in Sport.query.filter_by(sport='Kergejõustik').all()], coerce=int)
return form_class
def on_model_change(self, form, model, is_created):
/r/flask
https://redd.it/akfx0j
reddit
r/flask - Flask-Admin SelectField Choices, not a valid option.
1 vote and 0 comments so far on Reddit
Access the text added using javascript to html file using flask.
I am trying to create a todo list using html, javascript and flask. In my todo list, I add my lists of tasks using javascript.
How can I print out my added list using python?
​
`<!DOCTYPE html>`
`<html>`
`<head>`
`<title>Daily Goals</title>`
`<link rel="stylesheet" href="{url_for('static',filename='stylesheet/daily.css')}">`
`</head>`
`<body>`
`<script type="text/javascript" src="{url_for('static',filename='stylesheet/daily.js')}"></script>`
`<div class="addItem">`
`<input type="text" id="myInput" placeholder="text...">`
`<span onclick="newDiv()" class="addList">Add</span>`
`</div>`
`<form method='POST' action='/paras'>`
`<div class="covered" id="fullOn">`
`<h2 id="para">Add your daily todo lists</h2>`
`</div>`
`<div class="item"> #This is where my javascript will add my list.`
`<p>{itemName}</p>`
`</div>`
`<p><input value = "Do it" type='SUBMIT'></p>`
`</form>`
`</body>`
`</html>`
/r/flask
https://redd.it/c18sik
I am trying to create a todo list using html, javascript and flask. In my todo list, I add my lists of tasks using javascript.
How can I print out my added list using python?
​
`<!DOCTYPE html>`
`<html>`
`<head>`
`<title>Daily Goals</title>`
`<link rel="stylesheet" href="{url_for('static',filename='stylesheet/daily.css')}">`
`</head>`
`<body>`
`<script type="text/javascript" src="{url_for('static',filename='stylesheet/daily.js')}"></script>`
`<div class="addItem">`
`<input type="text" id="myInput" placeholder="text...">`
`<span onclick="newDiv()" class="addList">Add</span>`
`</div>`
`<form method='POST' action='/paras'>`
`<div class="covered" id="fullOn">`
`<h2 id="para">Add your daily todo lists</h2>`
`</div>`
`<div class="item"> #This is where my javascript will add my list.`
`<p>{itemName}</p>`
`</div>`
`<p><input value = "Do it" type='SUBMIT'></p>`
`</form>`
`</body>`
`</html>`
/r/flask
https://redd.it/c18sik
reddit
r/flask - Access the text added using javascript to html file using flask.
1 vote and 7 comments so far on Reddit
I just made the most 50/50 script ever: it selects and opens random image URLs from 4chan (returns NSFW results like half of the time)
It's fun to run! Cause you *really* never know what's going to pop up. Run at your own risk though, cause it can return anything from cute kitten pictures, to not-unseeable NSFL pictures
#!/usr/bin/python3
#*************************************************************************************************************************
#IMPORTANT
#Don't remove the time.sleeps; which are in place to comply with 4chan's API rule of 'no more than 1 request per second'
#https://github.com/4chan/4chan-API
#
#This script selects a random images from 4chan, and opens them in web browser
#Requires the 'requests' module
#*************************************************************************************************************************
import requests,random,json,time,webbrowser
#Returns [ random image URL, random image's thread URL ]
def r4chan():
#List of 4chan boards
boards = ['a','c','w','m','cgl','cm','n','jp','vp','v','vg','vr','co','g','tv','k','o','an','tg','sp','asp','sci','int','out','toy','biz','i','po','p','ck','ic','wg','mu','fa','3','gd','diy','wsg','s','hc','hm','h','e','u','d','y','t','hr','gif','trv','fit','x','lit','adv','lgbt','mlp','b','r','r9k','pol','soc','s4s']
#Select a board
board = random.choice(boards)
#Request board catalog, and get get a list of threads on the board; then sleeping for 1.5 seconds
threadnums = list()
/r/Python
https://redd.it/ccrh6o
It's fun to run! Cause you *really* never know what's going to pop up. Run at your own risk though, cause it can return anything from cute kitten pictures, to not-unseeable NSFL pictures
#!/usr/bin/python3
#*************************************************************************************************************************
#IMPORTANT
#Don't remove the time.sleeps; which are in place to comply with 4chan's API rule of 'no more than 1 request per second'
#https://github.com/4chan/4chan-API
#
#This script selects a random images from 4chan, and opens them in web browser
#Requires the 'requests' module
#*************************************************************************************************************************
import requests,random,json,time,webbrowser
#Returns [ random image URL, random image's thread URL ]
def r4chan():
#List of 4chan boards
boards = ['a','c','w','m','cgl','cm','n','jp','vp','v','vg','vr','co','g','tv','k','o','an','tg','sp','asp','sci','int','out','toy','biz','i','po','p','ck','ic','wg','mu','fa','3','gd','diy','wsg','s','hc','hm','h','e','u','d','y','t','hr','gif','trv','fit','x','lit','adv','lgbt','mlp','b','r','r9k','pol','soc','s4s']
#Select a board
board = random.choice(boards)
#Request board catalog, and get get a list of threads on the board; then sleeping for 1.5 seconds
threadnums = list()
/r/Python
https://redd.it/ccrh6o
reddit
r/Python - I just made the most 50/50 script ever: it selects and opens random image URLs from 4chan (returns NSFW results like…
134 votes and 24 comments so far on Reddit
My first useful script. Clear windows print server queue.
Greetings all!,
​
This is my first useful python script, albeit a really simple one. It's purpose: At my place of work we have tons of clients that often try to print some weird ass files on the windows print server, only to lock it up.
It's not that hard to remote in to the server, stop the print service, clear the print queue, and restart the service. However, it is indeed tedious, and happens all too often affecting departments at a time. Therefore, I went ahead and made this script. It handles all those tasks for you. It needs to be ran as admin to work, and has an admin privilege checker in there. Not from scratch, I'm still new, I have taken a intro college course, but had to research some of these functions. It was not only copy and paste though, this was a learning experience for me as well.
Very useful for managed service providers, or the lazy sysadmin.
I call it: The spooler nuke.
#The purpose of this program is to kill the print service, delete print queue, restart print service.
#This script can be useful for clients who rely on the
/r/Python
https://redd.it/ef7324
Greetings all!,
​
This is my first useful python script, albeit a really simple one. It's purpose: At my place of work we have tons of clients that often try to print some weird ass files on the windows print server, only to lock it up.
It's not that hard to remote in to the server, stop the print service, clear the print queue, and restart the service. However, it is indeed tedious, and happens all too often affecting departments at a time. Therefore, I went ahead and made this script. It handles all those tasks for you. It needs to be ran as admin to work, and has an admin privilege checker in there. Not from scratch, I'm still new, I have taken a intro college course, but had to research some of these functions. It was not only copy and paste though, this was a learning experience for me as well.
Very useful for managed service providers, or the lazy sysadmin.
I call it: The spooler nuke.
#The purpose of this program is to kill the print service, delete print queue, restart print service.
#This script can be useful for clients who rely on the
/r/Python
https://redd.it/ef7324
reddit
My first useful script. Clear windows print server queue.
Greetings all!, This is my first useful python script, albeit a really simple one. It's purpose: At my place of work we have tons of...
Can I run AWS functions in Flask?
Hey all, I am looking to create a flask site that I can use my push buttons to run aws commands against my aws account, mainly to just run lambda functions I created. Was wondering if that was even possible? I have tried many things but still a no go. I posted below snippets of the code and wanted to see if I am on the right track if it is at all possible. flask site runs fine, just when I hit the push button it fails since im not sure if my code route is even functioned properly, I have also tried with just the def, also will be posted below
Thanks so much!
​
from botofunctions import * #this is the file that holds functions
EXAMPLE1:
@app.route('/do_something', methods=['POST'])
def do_something():
msg = getcaller() # this function is just running aws sts g-c-i
return msg
EXAMPLE2:
@app.route('/do_something', methods=['POST'])
def do_something():
/r/flask
https://redd.it/gkhliq
Hey all, I am looking to create a flask site that I can use my push buttons to run aws commands against my aws account, mainly to just run lambda functions I created. Was wondering if that was even possible? I have tried many things but still a no go. I posted below snippets of the code and wanted to see if I am on the right track if it is at all possible. flask site runs fine, just when I hit the push button it fails since im not sure if my code route is even functioned properly, I have also tried with just the def, also will be posted below
Thanks so much!
​
from botofunctions import * #this is the file that holds functions
EXAMPLE1:
@app.route('/do_something', methods=['POST'])
def do_something():
msg = getcaller() # this function is just running aws sts g-c-i
return msg
EXAMPLE2:
@app.route('/do_something', methods=['POST'])
def do_something():
/r/flask
https://redd.it/gkhliq
reddit
Can I run AWS functions in Flask?
Hey all, I am looking to create a flask site that I can use my push buttons to run aws commands against my aws account, mainly to just run lambda...
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
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
reddit
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...
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
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
reddit
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...
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
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
reddit
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: ...
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
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
reddit
Image object being created on local host but not on heroku? whats...
here is the view: def img_upload(request,case_id): #this is only to add photos if request.method == "POST": case...
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
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
GitHub
GitHub - pravee42/simpletwitter: Twitter bot module with few lines of code
Twitter bot module with few lines of code. Contribute to pravee42/simpletwitter development by creating an account on GitHub.
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}
initialdata = 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
views.py
def WantListUpdateView(request, pk, username=None):
context = {}
def getusername(self):
username = self.request.user.username
context['data'] = {'username' : username}
initialdata = 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
reddit
Help with UpdateView and getting key:value from ModelForm
views.py def WantListUpdateView(request, pk, username=None): context = {} def get_username(self): username =...
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
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
GitHub
GitHub - Digital-Sapphire/PyUpdater: Pyinstaller auto-update library
Pyinstaller auto-update library. Contribute to Digital-Sapphire/PyUpdater development by creating an account on GitHub.
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
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
reddit
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...
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
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
Reddit
From the flask community on Reddit
Explore this post and more from the flask community
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
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
Reddit
From the djangolearning community on Reddit
Explore this post and more from the djangolearning community
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
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
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
Reddit
From the flask community on Reddit
Explore this post and more from the flask community
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
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
Reddit
From the flask community on Reddit
Explore this post and more from the flask community