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
<div class="col-3 text-center">
<h5>Child #1: </h4>
</div>
<div class="col-2 text-center">
{{ child.kg }}
</div>
<div class="col-2 text-center" >
{{ child.material }}
</div>
<div class="col-2 text-center" >
{{ child.box_price }}
</div>
<div class="col-3 text-center">
<button type="button" id='remove_box_0' class="btn btn-danger">Remove box</button>
</div>
{% endfor %}
</div>
</div>
</div>
<p>
{{ child_form.management_form }}
<input id="create" class="btn btn-secondary btn-lg btn-block btn-option btn-form" type="submit" value="Crear" />
</p>

javascript

// Adds the difference between desired boxes and current boxes
function add_boxes(form_id, total, num){
for (let i = total; i != total+num; i++) {
var element = $('#nested_forms_' + form_id + "> :first-child ").clone().css('display', 'none');
element.appendTo('#nested_forms_' + form_id).show('250');
};
$('#id_child-TOTAL_FORMS').val(num + total);
};

// Removes every unneeded boxes
function remove_boxes(form_id, total){
$('#nested_forms_' + form_id).children().each(function(){
if ($(this).index() >= total) {
$(this).fadeTo(150, 0).slideUp(150, function(){
$(this).remove();
});
}
});
$('#id_child-TOTAL_FORMS').val(total);
}

/r/django
https://redd.it/8ggdy2
Announcing Hack for the Sea 2018: Sept 22-23 in Gloucester MA

Hi everybody, we are happy and proud to announce the **3rd Annual Hack for the Sea** being held Sept 22-23 at the American Legion in Gloucester, MA

If you don't know, a "hackathon" is an attempt to ideate and make progress toward solutions to shared challenges. Hack for the Sea is slightly different than many other hackathons in that:

* It focuses on marine science exclusively
* All submissions must be released as open source
* It is meant to be a healthy, inclusive, and outcome-driven event.

This year's challenges come from our beneficiary organizations: the Consortium of Universities for the Advancement of Hydrologic Science, Inc. (CUAHSI), the Gloucester Marine Genomics Institute (GMGI), The Massachusetts Division of Fisheries and Wildlife, Ocean Alliance, and the MassBays National Estuary Program.

1. How does a changing coastal watershed impact coastal waters?
2. Where and when will Cod spawning occur?
3. Can a whale be identified based on their blowholes?
4. Can a mooring be designed that is not only eelgrass-friendly, but also user-friendly?

Ask me anything!

Early-bird Tickets are available here: https://www.eventbrite.com/e/hack-for-the-sea-2018-tickets-45603855359

/r/pystats
https://redd.it/8gqxoo
Update photo category with ajax.

So I want to implement a select drop-down element which on change should update the images shown based on the selected category. I created the models and referenced the "categories" model from a "post image" model. I can get these categories show up on front end in a drop-down. My question is how to implement this with ajax? I am not sure how url matching plays a role on this. TY

/r/djangolearning
https://redd.it/8goftk
pyc files cached? Problem in production.

hi i have site deployed using nginx and gunicorn.

I decided I wanted to change something in a views.py file in production.
None of the changes have taken place.
I have already deleted the .pyc files. I have restarted nginx and gunicorn
i have also used --reload.

is there another place in the project that these pyc files are being cached?

/r/django
https://redd.it/8gv51q
Can you test login in shell?

As the question says. My first Django project had so many errors related to the login/authentication by the user that I had to forget about the whole project without being able to fix that which was the most important thing.

Right now, I found an awesome way to test my database/models by using the Shell before even setting up views/urls/templates and I'm so happy by doing it this way(so much relief), but when it comes to authenticating and login a user... I dont know about that. It can be a thing? Testing login/authentication via Shell?

Anyone faced a similar situation? Any help would be appretiate it, thanks for your time also.

/r/djangolearning
https://redd.it/8gwlii
flask-praetorian v0.4 release

I'm proud to announce the release of flask\-praetorian 0.4 today. This version comes with some bug fixes and api hardening. Most significantly, though, some improved documentation and lots of tutorial.

Pull\-requests and issues are very welcome!

[http://flask\-praetorian.readthedocs.io/en/latest/](http://flask-praetorian.readthedocs.io/en/latest/)

/r/flask
https://redd.it/8gs9mf
HELP - I want to build Dropbox or Google Drive clone practice project

Hello I need a help.

I want to develop Dropbox or Google Drive clone practice project.

There will be 3 models I guess: User (Uploader), Folder, File

Now what will be the relation between File and Folder to mimic many number of child folder depth?

For example, I want to implement this kind of url pattern in django:

/<parent_folder>/<next_folder_1>/<next_folder_2>/<next_folder_n>/files/

As you can see, the folders are not imaginable, user may go further into folder structure as their wish. It can be 5 folders or 3 folders or any number of folders. Each folder will have their corresponding files. Very much like dropbox or google drive. And how to visualize the parent child file/folder hierarchy in template?

Now how do I define this unknown number of folder depth pattern in django with one url pattern? So that, whatever folder a user go, the view will return files for this folder. The reference of this will be Dropbox and Google drive

Thanks in advance

/r/django
https://redd.it/8gtois
Undeclared variable with "dictionary" syntax does not throw exception

I spent the last half hour debugging my script where I typed ":" instead of "=" when trying to update a variable.

So why does

a: "10"

not throw an exception? Even when ``a`` is not defined prior to this?

/r/Python
https://redd.it/8gx5dc
Crypto trading bot think-tank: what indicators do you use?

I've been working on a python based trading bot using the GDAX api and have come pretty far. My ideas are working well, but still in the baby stages of testing. This thread is simply to see if there are others who are doing this who would like to pool statistics and indicator techniques.

I'm not talking so much about sharing our entire scripts but discussing what styles of analysis you have found useful, if any?

/r/pystats
https://redd.it/8h085p
[AF] How to properly test view functions?

So I have this view function:

@app.route('/submit', methods=['GET', 'POST'])
@login_required
def submit():
"""View function for the submit site, which contains a standard
form. Creates initial variables for mutable variables like
upvotes, downvotes and importance, to avoid any TypeErrors."""
form = SubmitForm()
if form.validate_on_submit():
post = Post(title=form.title.data, text=form.text.data, user_id=current_user.id, topics=[Topic(tag_name=form.topics.data)])
post.upvotes = 1
post.downvotes = 0
post.importance = 1
post.score = post.get_score()
db.session.add(post)
db.session.commit()

flash('You have now made a post!')
return redirect(url_for('index'))
return render_template('submit.html', title='Submit', form=form)

How would I properly test this works?

The testing function I'm using is this:

def test_submit(self):
"""Tests to see whether the /submit route will work"""
self.post = Post(title="Title", text="Text", user_id=1, topics=[Topic(tag_name="topic1"), Topic(tag_name="topic2")])
self.post.upvotes = 1
self.post.downvotes = 0
self.post.importance = 1
self.post.score = self.post.get_score()
db.session.add(self.post)
db.session.commit()
self.assertTrue(Post.query.filter_by(text="Text").first())
self.assertFalse(Post.query.filter_by(text="Not me").first())

I know this isn't the proper way of doing things, so how should I do it?

Here is the rest of my testing file, if needed:

https://github.com/ModoUnreal/dopenet/blob/master/tests/test_posts.py

/r/flask
https://redd.it/8h19nu
[AF] How do I send data route to route, in order to maintain a dynamic form?

This question is probably not asked correctly. I'll try to explain better below. I am also new to python and flask.

I am creating a flask web interface for a simple inventory system we have. I'm trying to have the following interaction:

USER: <Inputs part number into appropriate field>
SERVER: <Checks to see if on file>

if on file

SERVER: "Place bin on scale."
USER: <Places bin on scale>
*SCALE: <Weighs item and sends value to server>

*My issue

Here is my issue: the scale data sent is not within scope of the "inventory" route. Is there a better way to go about this?

**My Direction:**

I want the user to have the form readily available for another form input if necessary. I also want to print the new data with some data pulled from the database after the item is weighed.

**app/routes.py**

from flask import render_template, flash, redirect, url_for, request, jsonify
from app import app, db
from app.forms import LoginForm, RegistrationForm, PrintLabelForm, \
InventoryForm1, InventoryForm2
from flask_login import current_user, login_user, logout_user, login_required
from app.models import *
import scale as s

@app.route('/inventory', methods=['GET', 'POST'])
@login_required
def inventory():
form = InventoryForm1()
# if form.validate_on_submit(): # Checks form submission syntax validity
if "submit" in request.form: # Checks form submission syntax validity
item = Items.query.filter_by(ItemCode=form.itemCode.data).first()
measurement = Measurements.query.filter_by(partNumber=form.itemCode.data).first()

# Checks if part number field is correct
if item is None: # No input for the field
flash('Item not on file.')
return redirect(url_for('inventory'))
elif measurement is None: # No current measurements available
flash('No previous measurements found for, ' + item.ItemCodeDesc + '.')
flash('Place empty container on scale.')
# while container is not containerChange and keyboardIdle:
# await item data input
else: # Generate Item Report
flash('Place bin on scale.')
# User clicks "Weigh Item"

return render_template('inventory.html', title='Inventory', form=form)

@app.route('/weighItem', methods=['GET', 'POST'])
@login_required
def weighItem():
weight = s.runScale("getWeight", 0)
return jsonify(weight=weight)

**app/templates/base.html**

<script>
function weighItem() {
$.post('/weighItem', {
}).done(function(response) {
$("#result").text(response.weight);
alert(response.weight);
}).fail(function() {
$.text("Error: Could not contact server.");
});
}
</script>

**app/templates/inventory.html**

{% extends "base.html" %}
{% import 'bootstrap/wtf.html' as wtf %}

{% block app_content %}
<h1>Inventory</h1>
<div class="row">
<div class="col-md-4">
{{ wtf.quick_form(form) }}
<a href="javascript:weighItem()" id="weighItem">Weigh Item</a>
<p id="result"> </p>
</div>
</div>
{% endblock %}



**Some Notes:**

I am using the [https://github.com/tatobari/hx711py](https://github.com/tatobari/hx711py) for a scale.

/r/flask
https://redd.it/8h0ur9
django-bootstrap-datepicker-plus: Django Widget for bootstrap-datepicker for Django version 1.8, 1.10, 1.11 and 2.0.4.

I have published a date\-picker widget [django\-bootstrap\-datepicker\-plus](https://github.com/monim67/django-bootstrap-datepicker-plus) for `django` to support latest version keeping backward compatibility up to`djang`o version 1.8. Please let me know what you think of it. Any suggestion is highly appreciated and is what I am looking for.

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