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
What is a good first project for someone interested in machine learning?

I know a little bit of C but I am mainly learning on Python. I would like to start building something myself soon and I'm interested in machine learning and data science, but I am not sure where to start.

/r/Python
https://redd.it/8rm7m8
Question of how db.relationship() links databases together

Consider this bit of code from the mega tutorial:

class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(64), unique = True)
email = db.Column(db.String(120), unique=True)
password_hash = db.Column(db.String(128))
posts = db.relationship('Post', backref = 'author', lazy = 'dynamic')

def __repr__(self):
return '<User {}>'.format(self.username)

class Post(db.Model):
id = db.Column(db.Integer, primary_key = True)
body = db.Column(db.String(140))
timestap = db.Column(db.DateTime, index = True, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

def __repr__(self):
return '<Post {}>'.format(self.body)


 

The general goal here is for every post to be linked to an author, in a one to many relationship (as in a user object can have many posts).

But I'm not exactly sure what the implementation doing.

In

`posts = db.relationship('Post', backref = 'author', lazy = 'dynamic')`

is backref just an additional field that `posts` is feeding to a Post object, that happens to be the `ForeignKey` defined in the `user_id` field? I'm just confused how `posts` and `user_id` link together so that each user can have various blog posts linked to him.

thanks in advance!

/r/flask
https://redd.it/8re0b5
How do I override the admin model delete action with confirmation beforehand?

I am trying to modify the bulk delete action that comes default with any registered model in the admin.

My goal is to override it and add in some extra functionality. This has actually been successful, but I lose the confirmation page beforehand. What happens instead is that the delete action fully executes and returns me back to the model's list view immediately. I want to keep the confirmation page as an intermediary *before* my action goes ahead and performs its customized deletion behavior on my selected objects.

Unfortunately, I've gotten a bit stuck on how to do this. Does anyone know how it can be done?

So far, my code is as follows:

class ImageAdmin( admin.ModelAdmin ):
form = ImageForm
actions = [ 'delete_selected' ]

def delete_selected( self, request, queryset ):
for obj in queryset:
obj.delete( )


admin.site.register( Image, ImageAdmin )

What can I do to make this work with the confirmation page?

/r/django
https://redd.it/8rnupm
Help in Python Simulation

Hello, i crunched numbers in calculating the position of the 3 body problem. I have 3.5 GB worth of data (x, y). But the problem is that i dont know how to use that data and plot it in such a way that it keeps updating in a reasonable amount of time (simulation visualization).

I just want a simple way to plot the 3 points and keeping it updating the positions while the program reads the file. Any help will be valuable.

/r/Python
https://redd.it/8rojtc
how could i make this, im a little lost

okay so ive been playing with django for some time and i have reached a point where im stuck i have this problem

lets say i have products and marketplaces
so i can create a product for example a cup, with their base values like name stock etc (i can already do that good)

then i can create marketplaces lets say i have one in the us and other in germany for example where i want to sell my cups and each marketplace has its own things also like name etc.

then my problem comes when i want to be able to put each product on X number of marketplaces independently with its own new values so for example my cup may have a german name on the german marketplace and the price in € for example.
thats where i have a problem right now i have 3 tables like
product
marketplace
product_marketplace

but i dont know how to make a form where you select a product and a marketplace and save them, thats my main problem
also i want the default values on that form to be the ones of the product for example the default name etc

i hope i was clear enought and thanks in advance!

/r/django
https://redd.it/8rpye2
Does anyone want a free Python or C tutor?

I'm really bored this summer and love teaching. We can do Skype lessons that are super flexible. PM me if you're interested

/r/Python
https://redd.it/8rq9z4
DataTables with Ajax

Hello everyone, I want to show a table on my website which will be automatically updated every X seconds (without refreshing the page). I really like what Django-Tables2 has to offer (filtering, pagination and etc), but it seems it cannot be used with JS for updates? Is there an another project which is updated regularly and has similar features?
Thanks in advance for the answers!

/r/django
https://redd.it/8rpbe2
How to manage/organize data across multiple apps.

Hey guys,

New to Django but not new to OOP/Python. Reading through Two Scoops and they're talking about isolating apps to do one thing clearly. As they setup apps, they have model.py files for each app.

What I'm trying to understand is -- for my application -- a lot of data would be used/analyzed in numerous different apps. From the DB/Models perspective, what is the best way to organize this?

/r/django
https://redd.it/8rrp8w
Django Datefield, TimeField, and DecimalField not displaying


Hi Djangonauts,
I am new to Django. Please forgive any silly mistakes in code or logic


My forms are not displaying the fields like they should(See Image).

The `price` field only lets me put numbers but there is no restriction on how many numbers It even lets me add a 15 digit number

The `date` and `time_from`, `time_to` fields just show long text-input fields. What am I doing wrong?


class LessonsForm(forms.ModelForm):
class Meta:
model = Lessons
fields = ('price', 'quantity', 'date', 'time_from', 'time_to')

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['quantity'].label = "How many members in one class"
self.fields['price'].label = "How much do members have to pay to take lessons from you"
self.fields['date'].label = "When do you plan to offer lessons"
self.fields['time_from'].label = "What time do the lessons start"
self.fields['time_to'].label = "What time does the lessons end"

widgets = {
'price': forms.DecimalField(decimal_places=2, max_digits=5),
'quantity': forms.IntegerField(min_value=1, max_value=25),
'date': forms.DateField(format("%b %d %Y")),
'time_from': forms.TimeField(format('%H:%M')),
'time_to': forms.TimeField(format('%H:%M'))
}

**Below are the models**

class Lessons(models.Model):
user = models.ForeignKey(User)
post = models.ForeignKey(Post)
price = models.DecimalField(max_digits=5, decimal_places=2)
quantity = models.PositiveIntegerField()
date = models.DateField()
time_from = models.TimeField()
time_to = models.TimeField()


def get_absolute_url(self):
return reverse('posts:single', kwargs={'username': self.user.username,
'slug': self.post.slug})

**Below is the image of how the form now looks**

https://i.stack.imgur.com/ZtMvO.png

/r/django
https://redd.it/8rrrwt
My humble contribution to Python Statistics: A method to compute Percentiles with methods missing in Numpy
https://github.com/ricardoV94/stats/tree/master/percentile

/r/pystats
https://redd.it/8rr5r7
I also wanna teach someone python, C, web scraping, sql, etc for free

Hey guys I’m inspired by another op here. I’m still an undergrad so I may not be able to teach you advanced stuffs. Here is my recent side project which may illustrate my ability. http://uoftprofs.com

If u r interested in this, feel free to pm me. (Btw my purpose of doing this is to make my English more fluent :p) I will take my lessons seriously I promise.

/r/Python
https://redd.it/8rqtu5
Is there an easy way/best practice for encrypting a field in a table?

I have a column of Tax Identification Numbers, kind of like SSN, but for businesses. It seems like a good idea to encrypt these.

I'll need to pull them back out, so hashing won't work.

/r/djangolearning
https://redd.it/8rokae
Handling conditional html formating ?

In one of my html pages I have the following:

{% for bet in recent_bets %}
{% if bet.status__name == "Won" or bet.status__name == "Half Won"%}
<div class="container col recent-form_col bg-success" data-toggle="tooltip" data-placement="top" title="{{ bet.status }}">
{% elif bet.status__name == "Lost" or bet.status__name == "Half Lost"%}
<div class="container col recent-form_col bg-danger" data-toggle="tooltip" data-placement="top" title="{{ bet.status }}">
{% elif bet.status__name == "Void" or bet.status__name == "Cancelled"%}
<div class="container col recent-form_col bg-secondary" data-toggle="tooltip" data-placement="top" title="{{ bet.status }}">
{% elif bet.status__name == "Cash Out" %}
<div class="container col recent-form_col bg-warning" data-toggle="tooltip" data-placement="top" title="{{ bet.status }}">
{% endif %}

Based on what the bet.status__name is, it returns a different background color ex bg-success.

Apart from this case, I have a few other cases similar to that.

I would like to know how do you handle these things. Just leave it in the html, create a filter/tag that returns the appropriate html or something else ?

It might not seem a big deal, but I would like to follow good practices whenever I can.

/r/django
https://redd.it/8rmueg
My humble contribution to Python Statistics: A method to compute Percentiles with methods missing in Numpy
https://github.com/ricardoV94/stats/tree/master/percentile

/r/Python
https://redd.it/8rr2o6
Role, Permission, User in Flask

Hi!

I have 3 tables in my database:

User ->Standard user table

Role->Which represent groups that users can belong to e.g. Operator, Admin, UsualUser

Permission->Table with permissions e.g. "can edit", "can delete" etc.

All 3 of them are connected via foreign keys with many to many relationship:

User <-> Role <-> Permission

What kind of extension should I use to make use of them? I found: Flask-Principal, Flask-Allows, Flask-RBAC but I don't think they will suit my needs. What I am trying to achieve is to deny access to specyfic routes using e.g. decorators like this:

@blueprint.route('/users/<string:uuid>', methods=\['GET'\])

@HERE DECORATOR WHICH AUTHORIZE BASED ON ROLE-PERMISSION DATABASE MODEL
def get\_user(uuid):
user\_with\_known\_id = User.query.filter\_by(uuid=uuid).first()
return jsonify(user\_with\_known\_id.to\_dict())

/r/flask
https://redd.it/8rstzr
Should I convert from pymysql to flask-alchemy?

Hi everyone. I currently have a web app using flask for the app routes and pymysql for grabbing data from an amazon RDS.

My question is, I’ve heard a lot about flask-SQLAlchemy, but not quite sure what the benefit of using it is compared to my current solution. Would it be worth rewriting my application to use flask sql and if yes why? What is the main benefit?

I know some of this can be answered with google but I couldn’t really see any strong reason to switch and am wondering if I missed anything important.

Thank you all

/r/flask
https://redd.it/8rt2rz
To SPA or not to SPA ? (Existing product)

Backstory:

We've got an existing SaaS product, chugging along with the Django templating engine and an old Bootstrap template bought for $20 several years ago. We're a growing team of mostly backend developers, and now have this nice and fancy 2018 re-design of our dashboard lying in front of us that we need to implement for several reasons (current design is not easily extendable as it was not custom made for our requirements, everyone from clients to sales complains that it looks old and feels chunky, etc..).

From where I'm sitting, we have several options:

1. Hire an experienced frontend developer (that's comfortable with a framework such as React), and have that person tag team with someone from the backend to create an API + SPA.

Pros: Decoupled approach makes things easier/quicker to develop the product further as everyone just concentrates on what they do best.

Cons: Going will be slow as no backend API exists at this point AND we will have to support 2 applications going forward. The complete responsibility of the frontend will lie with the sole frontend developer now and in the future, as we will always be a backend heavy team that will not be able to help with the frontend if necessary.

2. Hire a mid-level frontend developer: stick with Django templates, get frontend dev to upgrade current template to latest bootstrap(or whatever works and is popular these days), and implement new design.

Pros: No API needed, backend team can continue working on product roadmap. Will have to support only 1 app. Backend devs will be comfortable fixing bugs/supporting frontend code if necessary.

Cons: Lose out on super cool new frontend tech(?), oldschool approach ?

3. Hire an experienced frontend developer and do a hybrid approach (page-as-a-component ? [https://hackernoon.com/reconciling-djangos-mvc-templates-with-react-components-3aa986cf510a](https://hackernoon.com/reconciling-djangos-mvc-templates-with-react-components-3aa986cf510a))

I'd love to hear from someone that grew a project and a team and had to face a similar decision. Time and resources are limited here, we have a product roadmap to stick to to stay competitive, and making this frontend upgrade seems almost as necessary as pushing out new features.

Thanks in advance!

/r/django
https://redd.it/8rd4dr