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
KeyError when the key exists

*Solved:*

Thanks u/vikingvynotking. The `format()` method required explicitly setting the key/value pair as opposed to just the positional argument. Changing it to:

`success_message = REGISTRATION_SUCESS.format(username=request.POST['username'])`

fixed the `KeyError`. However the message still isn't being displayed but I've yet to work on that :)

\--------------------------------------------------

*Goal:*

After a user registers via a form, have CreateView provide a message welcoming that user, using the username supplied with the POST data.

*Method:*

Override the CreateView's `post()` method to access the `request` object and its `POST` dict to retrieve the provided username.

*Problem:*

**Django/Python throws a** `KeyError` **suggesting that the key doesn't exist.** Looking at the values available to the method, the key does, in fact, appear to exist.

*Possible Solution:*

Could this have something to do with CBVs being instantiated when Django first runs and therefore any POST data doesn't yet exist? I had a similar problem with trying to use `reverse()` for success URLs, but that was an easy switch to `reverse_lazy()`.

*Traceback:*

ERROR:django.request:Internal Server Error: /accounts/register/
Traceback (most recent call last):
File "/home/dedolence/Documents/projects/mocktions2/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/home/dedolence/Documents/projects/mocktions2/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response


/r/djangolearning
https://redd.it/y8abcq
Thursday Daily Thread: Python Careers, Courses, and Furthering Education!

Discussion of using Python in a professional environment, getting jobs in Python as well as ask questions about courses to further your python education!

This thread is not for recruitment, please see r/PythonJobs or the thread in the sidebar for that.

/r/Python
https://redd.it/y8iisy
If you could rename 1 component of the Python language, which one would it be?

We all know that naming things is notoriously hard and it is easy to judge in hindsight.

That being said, if you could change the name of one Python function/method/keyword etc., which one would it be? Can you suggest a more intuitive name?
It can be part of the core language, the standard library, or some third-party package.

Recently, I watched a talk by Raymond Hettinger where he would rename the else clause in Python for-loops to nobreak from today's perspective.

Personally, I have a hard time remembering what dict.setdefault() does. For some reason, I immediately connect the word default to initializing some kind of object rather than updating some value.

Excited to hear your picks!

/r/Python
https://redd.it/y887d1
Honest question: Why must "self" always be passed in as parameter, why wasn't it made a built-in?

In most of my conversations with fellow Rubyists on language wars, this point always comes up. For one, when you always precede the "self" parameter (like in below code), there is an ambiguity. For example, you actually have 3 parameters but when you call it, it only has 2. Another problem is the obvious redundancy and repetition of the "self" keyword here. My question is:

1. Why was it so important for designers of the language to make declaration of self parameter so explicit? Having a built-in self object for the class instance like Java's this or PHP's $this should have been a no brainer.
2. Going forward, are there any plans to fix this in a future Python version by making self a built-in?


class Animal:

# instance attributes
def init(self, name, family):
self.name = name
self.family = family

# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)

def dance(self):
return "{} is now dancing".format(self.name)

/r/Python
https://redd.it/y8ofb6
count

i am counting certain toners in stock with the below query.it works fine until the last item .but after the last item the remining_qty field doesn't update to zero.as you can see i am updating my remaininy_qty field based on the count of tonerdetails in stock.

def calcremainingqty():
for toner in Toners.objects.filter(tonerdetailsstatus="In-Stock").annotate(tonerdetailscount=Count('tonerdetails')):
toner.remaining
qty = toner.tonerdetailscount
toner.save(updatefields='remaining_qty')

below is my toner and toner details models.

class Toners(models.Model):

tonermodel = models.CharField(maxlength=10,null=True)
tonerprinter = models.ForeignKey(Items,ondelete=models.CASCADE)
totalqty = models.PositiveIntegerField(default=0,null=True)
remaining
qty = models.PositiveIntegerField(default=0,null=True)
created=models.DateTimeField(default=datetime.now())
objects = models.Manager()

class TonerDetails(models.Model):
STATUS =
('In-Stock', 'In-Stock'),
('Out-of-Stock', 'Out-of-Stock'),



/r/django
https://redd.it/y8sh6f
All Data Structures and Algorithms Concepts and Solutions Stored in a Structured Manner 🎯🔥

Repository Link: **https://github.com/SamirPaul1/DSAlgo**

In this repository, I have stored solutions to various problems and concepts of Data Structures and Algorithms in Python3 in a structured manner.

Topics Covered:

[Dynamic Programming](https://github.com/SamirPaul1/DSAlgo/tree/main/02_Dynamic-Programming)
**Sorting Algorithms**
[LinkedList](https://github.com/SamirPaul1/DSAlgo/tree/main/04_LinkedList)
**Object-Oriented Programming**
[Binary Trees](https://github.com/SamirPaul1/DSAlgo/tree/main/06_Binary-Trees)
**Graph Algorithms**
[Heap](https://github.com/SamirPaul1/DSAlgo/tree/main/08_Heap)
**Matrix**
[Trie](https://github.com/SamirPaul1/DSAlgo/tree/main/10_Trie)
**Binary Search**
[Backtracking](https://github.com/SamirPaul1/DSAlgo/tree/main/12_Backtracking)
**Stack**
[Queue](https://github.com/SamirPaul1/DSAlgo/tree/main/14_Queue)
**Greedy**
[String](https://github.com/SamirPaul1/DSAlgo/tree/main/16_String)
**Bit Manipulation**
[Array](https://github.com/SamirPaul1/DSAlgo/tree/main/18_Array)
**HashMap**
[DFS BFS](https://github.com/SamirPaul1/DSAlgo/tree/main/20_DFS-BFS)
**Two Pointers**
[Math](https://github.com/SamirPaul1/DSAlgo/tree/main/22_Math)
**Recursion**

In various folders of the above topics, you can find questions and concepts related to that topic.

In the [Dynamic Programming](https://github.com/SamirPaul1/DSAlgo/tree/main/02_Dynamic-Programming) section, you can find all the questions covered and not covered in [Aditya Verma's](https://www.youtube.com/c/AdityaVermaTheProgrammingLord) [dynamic programming playlist](https://youtube.com/playlist?list=PL_z_8CaSLPWekqhdCPmFohncHwz8TY2Go) folder-wise with my [handwritten notes](https://raw.githubusercontent.com/SamirPaul1/DSAlgo/main/02_Dynamic-Programming/Dynamic-Programming-NOTE.pdf).✍️
If you are preparing for an interview from **Striver’s SDE Sheet** then the **30-Days-SDE-Sheet-Practice** will be helpful to you. Here I have stored solutions to questions of each day with short notes to each solution, as short notes about the approach are very helpful during revision.🎯
In the [Questions-Sheet](https://github.com/SamirPaul1/DSAlgo/tree/main/Questions-Sheet) directory, you can find questions asked by top product-based companies.
There is a collection of books and pdfs on various important computer science fundamentals in the **BOOKS-and-PDFs** directory.📚

​

I am continuously trying to improve this repository by adding new questions and concepts related to the respective topic. Please feel free to

/r/Python
https://redd.it/y8pqyi
D Call for questions for Andrej Karpathy from Lex Fridman

Hi, my name is Lex Fridman. I host a podcast. I'm talking to Andrej Karpathy on it soon. To me, Andrej is one of the best researchers and educators in the history of the machine learning field. If you have questions/topic suggestions you'd like us to discuss, including technical and philosophical ones, please let me know.

/r/MachineLearning
https://redd.it/y89xqw
Setup CORS on an application that uses two consist of two Flask Servers

This is an continuation my ongoing series of posts to try and understand how to implement certain functionality on an application that uses an unorthodox architecture. I cannot change the architecture as it was already setup this way to prevent Users from being able to access the API Server directly.

​

Post 1: Setup Client Side Session Variables

https://www.reddit.com/r/flask/comments/y30xli/cannot\_access\_session\_variable\_set\_using/

Post 2: CSRF Setup on Application

https://www.reddit.com/r/flask/comments/y79xtd/setup\_crsf\_protection\_on\_an\_application\_that/

​

To recap once again, I have an application that consists of two servers both use Flask. The first server (Frontend/ Proxy Server) is used for serving HTML pages and is also responsible for forwarding all the calls (including the AJAX calls) to the second server (API Server).

The API Server contains all the actual processing/ business logic of the application. All the calls from the first server is sent to the second server using Python Requests module.

The application is going to be hosted on Azure as Web Apps. The users would only be able to access the frontend server.

I am not all that experienced with Web Development hence am finding it difficult to understand how to implement some of these features in the weird configuration that my application uses. I would like setup

/r/flask
https://redd.it/y87c65
In which file should I put my code for exernal API calls ?

As the title says. I want to make an external API call (every 60 minutes) and put this data into my database. Then this data will be available because my django will function as my personal backend API.Now the big question, where do I put this external API code (Which should be executed every 60 minutes)? Maybe somwhere in my View ?I plan to do it this way so that I only have one call every 60 minutes instead calling the external API for every user who visits my page

/r/django
https://redd.it/y90q07
I wrote a simple CSS "style engine" for tkinter.

# tks (tkinter superset) *

>**TL;DR** I've written a very basic implementation of CSS stylesheet support for tkinter widgets. It *mostly* supports *most* of the common widgets, and includes features such as nested styles, reusable CSS variables, and (in my opinion) a simpler and more concise syntax.

[Here's a screenshot of a very basic project using this package.](https://imgur.com/a/cy7zEGd)

[Here's the GitHub repository.](https://github.com/piccoloser/tks)

This is an idea I've had for a while now, and I'm happy with the progress I've made so far. This is the result of a *lot* of practice making simple GUI applications with tkinter, and also a lot of research into software design and metaprogramming. I've created a very basic system with which a tkinter application can be styled using CSS.

So, why CSS? First, I like the syntax and it resonates more with me than a bunch of calls to `my_widget.configure()`; second, I find it helpful to separate the style of a program from the logic; third, I wanted to make something that someone besides myself would potentially get use out of.

In its current state it's pretty much just an **incomplete** CSS parser with a couple of wrappers around tkinter's `Widget`and `Tk`

/r/Python
https://redd.it/y90kh0
FlastAPI: A FastAPI-like interface for building APIs in Flask

Hi!

I've made a small plugin for Flask to enable building API endpoints with a FastAPI-like interface.

I'm not here start a religious war about which framework is best. They both have merit, and to each their own, I would say ;) But I found that FastAPI did a great job at integrating pydantic/type-annotations in an API building framework, and wanted to build something similar for Flask.

Current features are:

* path parameters using flask paths
* query parameters
* body parameters using pydantic
* depends (including context dependencies)
* dependency\_overrides

Note that these are my first steps in type annotations and I have yet to find out how this all reflects in IDEs. So any notes, tips and feedback is welcome.

Kinks may also arise, as I haven't really battle tested this yet.

You can find the code here: [https://github.com/maarten-dp/flastapi](https://github.com/maarten-dp/flastapi) and you can install it using `pip install flastapi`

Looking forward to reading your (constructive) feedback!

/r/Python
https://redd.it/y9n472
Python compiler nuitka

Just wanted to make people aware of nuitka, which is a python compiler.

I've really benefited from it, and donated $5, I feel like I should give more but thought I would try to get them more exposure.

Or maybe you all already know about it.

https://nuitka.net/pages/overview.html

/r/Python
https://redd.it/y9m7s7
Simplification writing tests for parameters of models fields

Module is simplify writing tests for parameters of models fields. Please can you look and get me feedback

Link:https://github.com/nongreen/djangotestparametersoffields

/r/djangolearning
https://redd.it/y9ma50
Django API Generator for DRF - MIT / Published on PyPI / Source LINK in comments
https://pypi.org/project/django-api-generator/

/r/django
https://redd.it/y9qz5l
Django performance model method queries

I have a model method which returns the value of a query (objects.get)

In the template I then access the query objects field via

{{MODEL.METHOD.FIELD1}}

If I do this multiple times e.g. for field 2, 3 etc... Will this perform the query multiple times?

If so would it be better to just get the object in the view and pass via context?

And would it make a difference if the method returned a query list via objects.filter?

/r/django
https://redd.it/y9ttks
Python 3.11 Release Stream hosted by Pablo Galindo and Leon Sandøy on Oct 24th

Hello from the Python Discord!

Last year when Python 3.10 released, we partnered with the Python Discord to showcase the new features of the language and highlight the developers who helped bring the new features to us. This year, we’re continuing that partnership to celebrate the coming release of Python 3.11.

Python Discord owner Leon Sandøy and Python 3.11 release manager Pablo Galindo Salgado will be hosting a release stream on Monday, October 24th. They’ll be joined by CPython core developers who worked on some of the features going into 3.11, walking us over some of the specifics and highlighting the development process.

Date: Monday, October 24th
Time: 5 pm UTC
Where: https://www.youtube.com/watch?v=PGZPSWZSkJI

Some of the more notable features in Python 3.11 include:

Exception Groups and except*
Addition of `tomllib` to the standard library.
A 10-60% speedup over Python 3.10, courtesy of the Faster CPython project.

You can see a more exhaustive list on the What's New page

You can watch the stream once it goes live on youtube. And join us over on the Python Discord for an AMA with the developers during the stream and stay after the stream to talk with other programmers about how the new version of python can

/r/Python
https://redd.it/y9ylkt