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 pass data from a button in the html page to a database?

I have to code a page that has a question, and 3 options to answer.
I have a page that display the questions and the 3 answers of every question, the questions are already stored in the database. Now my problem is how can I save the user choice for that specific question?
I have created a model to save the user choice, the user id, and the question id. But I'm having trouble to get witch button the user clicked for the answer.

#Here is the model
class UserVotes(models.Model):
id_user = models.CharField(max_length=10)
id_question = models.CharField(max_length=10)
choice_user = models.CharField(max_length=10)

#Here is the view
class QuestionListView(generic.ListView):
model = Question

def voteQuestion(request):
if 'Yes' in request.POST:
idQuestion = request.question.id
idUser = request.user.id
p = UserVotes(id_user=idUser, id_question=idQuestion, choice_user=1)
p.save()
elif 'No' in request.POST:
#same thing, the difference is the value of choice_user will be 2.

#the url.py
url(r'^question/$', views.QuestionListView.as_view(), name='question'),

#the html page
<button type="submit" name="Yes">Yes</button>
<button type="submit" name="No">No</button>

I've got several errors, the last one that came up is a http 405 error, method post not allowed.
If someone can help please, I've spend 2 nights and 1 day on this already haha. Thanks!!

/r/django
https://redd.it/8gae5m
Is it a bad idea to combine per-view and per-site caching?

I'm trying to invalidate the cache of an object's detail page when I save the object. e.g. when updating a blog post. When saving the post, I generate the cache key, using the URL of the post's detail page, and delete the item from the cache if the key exists.

If I use only [per-view caching](https://docs.djangoproject.com/en/2.0/topics/cache/#the-per-view-cache), setting a cache on the PostDetail page, the invalidation works fine.

But if I also enable [per-site](https://docs.djangoproject.com/en/2.0/topics/cache/#the-per-site-cache) caching, the invalidation doesn't work; changes to the post only appear on its detail page after the page's cache has expired.

And if I *only* use per-site caching, the invalidation also doesn't work (I *guess* the cache's key for that page is generated differently?).

Which leads me to wonder if combining both per-site and per-view caching is potentially bad... but I don't think I've read this anywhere.

Do you combine the two? Or just use one? I'm interested to hear how other people handle caching (and invalidation) in Django.

(I'm currently on my local dev server, using the `locmem.LocMemCache` caching backend.)

/r/django
https://redd.it/8jdyyd
Confusion with Path

Hey all, I understand that path should contain route, views, name and kwargs, however I am rather confused of each application. Currently learning from[https://docs.djangoproject.com/en/2.1/intro/tutorial01/#the-development-server](https://docs.djangoproject.com/en/2.1/intro/tutorial01/#the-development-server) and I will ignore kwargs for now. **Project: mysite | app: polls.**

#polls/urls
from django.urls import path

from . import views

urlpatterns = [
path('', views.index, name='index'),
]

Q1: Why is the route ' '?

Q2: Where does the name='index' arrive from? I understand names are optional but they are especially useful for references, how will I utilize this?

#mysite/urls
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]

Q3: Where do I grab the route from? And why is there a need for '/'?

Q4: "include('polls.urls'))" is a 'view' argument, is there no need to refer to a [view.py](https://view.py)?



Sorry for the long post, eager to get things right

/r/djangolearning
https://redd.it/9aq30n
Double Pendulum Errors

So i was following a tutorial by The Coding Train and tried to make a double pendulum in python I looked up how to do it using tkinter and now my pendulum kinda works.The problems are that my angles are inverted and it works if i enter in a normal angle like 180° but if I try to give it an angle like 1° it works for 2 secs and then gets a math overload.If anyone knows what is going on pls help.Here's the code:

*from* math *import* sin,cos
*import* tkinter *as* tk
l1,l2,m1,m2=85,85,5,5
*#The gravity is is negative as an work around for the angles problem.*
g=-9.81
class DoublePendulum(tk.Tk):
def \_\_init\_\_(self):
tk.Tk.\_\_init\_\_(*self*)
*self*.title("Double Pendulum")
*self*.canvas=tk.Canvas(*self*,width=600,height=600,background="#343434")
*self*.canvas.grid(row=0,column=0)
*self*.a1\_v=0
*self*.a2\_v=0
*self*.a1=1
*self*.a2=1
*self*.speed=0.1
*self*.after(1,*self*.Calculate)
def Calculate(self):
*self*.canvas.delete("pendulum")
*#all the math is from https://www.myphysicslab.com/pendulum/double-pendulum-en.html*
num1=(-g\*(2\*m1+m2)\*sin(*self*.a1))
num2=-m2\*g\*sin(*self*.a1-2\**self*.a2)
num3=(-2\*sin(*self*.a1-*self*.a2)\*m2\*(*self*.a2\_v\*\*2\*l1\*cos(*self*.a1-*self*.a2)))
deno1=l1\*(2\*m1+m2-m2\*cos(2\**self*.a1-2\**self*.a2))
*self*.a1\_a=(num1+num2+num3)/deno1
num4 = 2\*sin(*self*.a1-*self*.a2)
num5=(*self*.a1\_v\*\*2\*l1\*(m1+m2))
num6=g\*(m1+m2)\*cos(*self*.a1)
num7=*self*.a2\_v\*\*2\*l2\*m2\*cos(*self*.a1-*self*.a2)
deno2=l2\*(2\*m1+m2-m2\*cos(2\**self*.a1-2\**self*.a2))
*self*.a2\_a=(num4\*(num5+num6+num7))/deno2


*self*.a1\_v+=*self*.a1\_a\**self*.speed
*self*.a2\_v+=*self*.a2\_a\**self*.speed
*self*.a1+=*self*.a1\_v\**self*.speed
*self*.a2+=*self*.a2\_v\**self*.speed

/r/Python
https://redd.it/d77wo7
My first useful script. Clear windows print server queue.

Greetings all!,

&#x200B;

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
My Very First Python Project: The Twitter Slicer!

DISCLAIMER: I am a beginner, I just started coding this month and I am still very noobish. Criticisms and suggestions to improve are much appreciated.

#The Twitter Slicer!
Slice your text into tweetable chunks.

https://github.com/KenesuEXE/twitter-slicer

These are the different "modes" to this twitter thread maker:

Raw Slice
Cuts the text into strictly 280 character threads.

Clean Slice
Cuts in the nearest whitespace so it doesn't cut in the middle of words.

Counted Slice
Basically adds a counter (e.i. (1/3)) in the end of each tweet.

Merry Christmas Reddit! 🎄
My experience with coding has been very fun so far! Even though I know that this code is very amateur and inefficient, I am still very proud of what I have done since I am only self-taught and I only use a smartphone to code. I think I have very much more to learn and I am very excited to learn more and do more projects.

/r/Python
https://redd.it/kjx0th
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
Stripe for Saas

I am developing a SAAS multi-tenant application where I got,

class Firm(TenantModel): #the Tenant
pass

class CustomUser(TenantModel): #the Tenant Users
firm = models.ForeignKey(Firm)
pass

My question is where do I associate the subscription and customer object? I frankly don't understand those two objects from stripe. What I want is for a FIRM to choose and pay for the plan and let the users of that firm access it. Should I associate the customer object to CustomUser model? Do I have to create a customer in stripe for every user of a Firm or I don't know. I don't understand what is a subscription object and a customer object and how to relate them to my models. It would be a lot of help if you could explain in layman's terms. I did see this well-explained,typically%20mapping%20to%20a%20company%20or%20division%20of%20a%20company.,-In%20this%20case) article here,typically%20mapping%20to%20a%20company%20or%20division%20of%20a%20company.,-In%20this%20case) , but I couldn't understand the B2B part thoroughly. Thanks

/r/djangolearning
https://redd.it/pz3koi
AmbiguousForeignKeysError: Could not determine join condition between parent/child tables

I have two sqlite tables

class Character(db.Model):
...
relationships = db.relationship("Relationship", backref="character", passivedeletes=True)

class Relationship(db.Model):
id = db.Column(db.Integer, primary
key=True)

#The character the relationship is being created for
maincharacter = db.Column(
db.Integer, db.ForeignKey("
character.id", ondelete="CASCADE")
)
#The character the maincharacter is related to
relatedcharacter = db.Column(
db.Integer, db.ForeignKey("
character.id", ondelete="CASCADE")
)
#The type of relationship (Father, Mother, etc.)
relationship
type = db.Column(db.String(50))

This triggers the error

Could not determine join condition between parent/child tables on relationship Character.relationships - there are multiple foreign key

/r/flask
https://redd.it/q06d3a
Help Needed: I'm Trying to get Variables from the Load before // Load after Functions into the main function that serves my page. But I'm completely stuck on how.

So I'm making this web app using Flask, that returns Recipe's from the BreakFast API. To me it's the first time using Flask (although I did some python scripting before) and also the first time taking on a project with an API and using Bootstrap. So to summarize: I'm way out of my comfort zone.

\#What I'm doing

My program does the following:

1. Make call to the breakfast API, it returns a random recipe
2. Parse the response from that API to obtain things like recipe's. That looks like this:
3. Then I want to do an image search based on the RecipeName and obtain the URL for this. That also works using this section:
4. Then I render the page using:

\#The problem

The issue with this is that getting the Image URL takes a good few seconds and as a result reloading the page is very slow.

I'd like to speed this up, my first idea was to use the: Before request to set an initial recipe so I can render the page 1x on bootup which will be slow. And then after each request fetch a new Recipe for the next user. An alternative is to render the page, and only later add the image

/r/flask
https://redd.it/strrr2
Is there a way to cross-reference a pandas dataframe output on Jupyter Notebook?

I was reading this section:https://jupyterbook.org/en/stable/content/references.html#reference-tables

I want to create automatic references/indexes for some printed pandas df but I don't want to paste the text in the cell to use the {table} chunk. Is there a way I can directly reference the output of some Python code?

EDIT: I can't render/reproduce the glue examples from this page: https://jupyterbook.org/en/stable/content/executable/output-insert.html#the-glue-figure-directive

/r/JupyterNotebooks
https://redd.it/yg0k4r
Release: NiceGUI 1.2.7 with ui.download, easier color definitions, "aggrid from pandas dataframe" and much more

With 21 contributors the just released NiceGUI 1.2.7 is again a wonderful demonstration of the strong growing community behind our easy to use web-based GUI library for Python. NiceGUI has a very gentle learning curve while still offering the option for advanced customizations. By following a backend-first philosophy you can focus on writing Python code. All the web development details are handled behind the scenes.


### New features and enhancements
- introduce `ui.download`
- introduce color arguments for elements like ui.button that accept Quasar, Tailwind, and CSS colors
- allow running in Python’s interactive mode by auto-disabling reload
- allow creating ui.aggrid from pandas dataframe
- fix navigation links behind reverse proxy with subpath
- allow sending "leading" and/or "trailing" events when throttling
- raise an exception when hiding internal routes with app.add_static_files
- add “dark” color to ui.colors

### Documentation
- enhance Trello "drag and drop" example to use a ToDo data model
- add workaround to docs for native mode when WebView2Loader.dll fails load
- add documentation and demo about element borders inside a ui.card
- add hint about exception when running executable with no console on Windows

Of course the release also includes some bugfixes (see release notes for details). Thanks to everyone who was involved in making this release happen.

/r/Python
https://redd.it/12m03v5