Hashtag Search from Twitter and Tumblr and display Images as Gallery using Django
https://github.com/chamow97/snappy
/r/django
https://redd.it/8ggjnh
https://github.com/chamow97/snappy
/r/django
https://redd.it/8ggjnh
GitHub
chamow97/snappy
snappy - A tool to display images tagged with a given hashtag from Twitter and Tumblr as a gallery! :rocket:
Not getting the context data of dynamically-generated formset
Not getting the context data of dynamically\-generated formset
I've created a CreateView with a Parent form with multiple Children formsets created via Javascript, but I cannot access to the data of the form when I'm creating more than the extra value formsets:
\- If 'extra=1', I can create more than 1, but won't save any. If I just create 1, it will save it.
\- If 'extra=3', I can create more than 3, but won't save any. If I just create 3, it will save them.
I've looking for what to do without sucess until this morning, when I've noticed that the problem it's I'm not getting the 'value' of every field properly. I've printed the get\_context\_data\['child\_form'\] when I'm creating 3 child forms dynamically with extra=1 \(left\) and when I just have extra=3 and I don't create more dynamically \(right\) [https://www.diffchecker.com/XskfB9y3](https://www.diffchecker.com/XskfB9y3)
Seems like I'm not getting the values and I don't know why, so I'll be very happy if anyone can point out what I'm missing. Here's the relevant code:
[forms.py](https://forms.py)
class ParentForm(ModelForm):
class Meta:
model = Parent
exclude = ()
class ChildForm(ModelForm):
class Meta:
model = Child
fields = ....
ChildFormSet = inlineformset_factory(Parent, Child, form=ChildForm, can_delete=True, extra=1)
[views.py](https://views.py)
class ParentCreateView(LoginRequiredMixin, CreateView):
model = Entrada
fields = ...
def get_context_data(self, **kwargs):
data = super(ParentCreateView, self).get_context_data(**kwargs)
if self.request.POST:
data['child_form'] = ChildFormSet(self.request.POST)
data['materials'] = Material.objects.all()
else:
data['child_form'] = ChildFormSet()
data['materials'] = Material.objects.all()
return data
def form_valid(self, form):
context = self.get_context_data()
child_form = context['child_form']
with transaction.atomic():
self.object = form.save()
if child_form.is_valid():
child_form.instance = self.object
child_form.field1 = self.object.id
child_form.save()
return super(ParentCreateView, self).form_valid(form)
template.html
<form class="own-form" action="" method="post">
{% csrf_token %}
{% for hidden_field in form.hidden_fields %}
{{ hidden_field }}
{% endfor %}
<h2 class="text-center text-header"> New Entry</h2>
<div class="form-group">
{% for field in form.visible_fields %}
<div class="form-group row">
<div class="col-4 text-center">{{ field.label_tag }}</div>
<div class="col-8">{{ field }}</div>
{% if field.help_text %}
<small class="form-text text-muted">{{ field.help_text }}</small>
{% endif %}
</div>
{% endfor %}
</div>
<hr>
<div class="form-group form-material-box row form-0">
<div class="col-3 text-center">
<label>Total weight: </label>
<input type="number" id="kg_0">
</div>
<div class="col-3 text-center">
<label>Boxes to create: </label>
<input type="number" id="num_boxes_0">
</div>
<div class="col-3 text-center">
<label>Material: </label>
<br>
<select name="item_id" id="material_0">
{% for material in materials %}
<option value="{{ forloop.counter }}">{{ material }}</option>
{% endfor %}
</select>
</div>
<div class="col-3 text-center">
<button type="button" id="create_boxes_0" class="btn btn-danger">Create</button>
</div>
<!-- Nested forms with desired number of boxes -->
<div id="nested_forms_0">
<div class="row" id="box_0">
{% for child in child_form%}
Not getting the context data of dynamically\-generated formset
I've created a CreateView with a Parent form with multiple Children formsets created via Javascript, but I cannot access to the data of the form when I'm creating more than the extra value formsets:
\- If 'extra=1', I can create more than 1, but won't save any. If I just create 1, it will save it.
\- If 'extra=3', I can create more than 3, but won't save any. If I just create 3, it will save them.
I've looking for what to do without sucess until this morning, when I've noticed that the problem it's I'm not getting the 'value' of every field properly. I've printed the get\_context\_data\['child\_form'\] when I'm creating 3 child forms dynamically with extra=1 \(left\) and when I just have extra=3 and I don't create more dynamically \(right\) [https://www.diffchecker.com/XskfB9y3](https://www.diffchecker.com/XskfB9y3)
Seems like I'm not getting the values and I don't know why, so I'll be very happy if anyone can point out what I'm missing. Here's the relevant code:
[forms.py](https://forms.py)
class ParentForm(ModelForm):
class Meta:
model = Parent
exclude = ()
class ChildForm(ModelForm):
class Meta:
model = Child
fields = ....
ChildFormSet = inlineformset_factory(Parent, Child, form=ChildForm, can_delete=True, extra=1)
[views.py](https://views.py)
class ParentCreateView(LoginRequiredMixin, CreateView):
model = Entrada
fields = ...
def get_context_data(self, **kwargs):
data = super(ParentCreateView, self).get_context_data(**kwargs)
if self.request.POST:
data['child_form'] = ChildFormSet(self.request.POST)
data['materials'] = Material.objects.all()
else:
data['child_form'] = ChildFormSet()
data['materials'] = Material.objects.all()
return data
def form_valid(self, form):
context = self.get_context_data()
child_form = context['child_form']
with transaction.atomic():
self.object = form.save()
if child_form.is_valid():
child_form.instance = self.object
child_form.field1 = self.object.id
child_form.save()
return super(ParentCreateView, self).form_valid(form)
template.html
<form class="own-form" action="" method="post">
{% csrf_token %}
{% for hidden_field in form.hidden_fields %}
{{ hidden_field }}
{% endfor %}
<h2 class="text-center text-header"> New Entry</h2>
<div class="form-group">
{% for field in form.visible_fields %}
<div class="form-group row">
<div class="col-4 text-center">{{ field.label_tag }}</div>
<div class="col-8">{{ field }}</div>
{% if field.help_text %}
<small class="form-text text-muted">{{ field.help_text }}</small>
{% endif %}
</div>
{% endfor %}
</div>
<hr>
<div class="form-group form-material-box row form-0">
<div class="col-3 text-center">
<label>Total weight: </label>
<input type="number" id="kg_0">
</div>
<div class="col-3 text-center">
<label>Boxes to create: </label>
<input type="number" id="num_boxes_0">
</div>
<div class="col-3 text-center">
<label>Material: </label>
<br>
<select name="item_id" id="material_0">
{% for material in materials %}
<option value="{{ forloop.counter }}">{{ material }}</option>
{% endfor %}
</select>
</div>
<div class="col-3 text-center">
<button type="button" id="create_boxes_0" class="btn btn-danger">Create</button>
</div>
<!-- Nested forms with desired number of boxes -->
<div id="nested_forms_0">
<div class="row" id="box_0">
{% for child in child_form%}
Diffchecker
Diff Checker
Diff Checker is an online diff tool to compare text to find the difference between two text files
<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
<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
reddit
r/django - Not getting the context data of dynamically-generated formset
0 votes and 0 so far on reddit
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
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
Eventbrite
Hack for the Sea 2018
Take on challenges in marine science, research, and industry at The 3rd Annual Hack for the Sea.
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…
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…
Jupyter Notebook wins ACM award
http://news.berkeley.edu/story_jump/pioneering-data-science-tool-jupyter-receives-top-software-prize/
/r/Python
https://redd.it/8gpvaw
http://news.berkeley.edu/story_jump/pioneering-data-science-tool-jupyter-receives-top-software-prize/
/r/Python
https://redd.it/8gpvaw
Berkeley News
Pioneering data science tool — Jupyter — receives top software prize
The Association of Computing Machinery gave its 2018 software award to a project that evolved from Fernando Pérez’s grad-school project
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
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
reddit
Update photo category with ajax. • r/djangolearning
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...
The Python programming song found on youtube
https://www.youtube.com/watch?v=3UsKYsLSGpU
/r/Python
https://redd.it/8gs822
https://www.youtube.com/watch?v=3UsKYsLSGpU
/r/Python
https://redd.it/8gs822
YouTube
The Python Programming Song
Programming at university can be fun. We found our own way to access the Python programming language. Somehow. Meh.
A song for programmers and sexy coding.
Original songs covered:
"Yo Home To Bel Air" by The Fresh Prince (1992)
"U Can't Touch This" by…
A song for programmers and sexy coding.
Original songs covered:
"Yo Home To Bel Air" by The Fresh Prince (1992)
"U Can't Touch This" by…
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
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
reddit
pyc files cached? Problem in production. • r/django
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...
Square spiral with Python turtle GRAPHICS
https://www.youtube.com/watch?v=okIujaQCfOw&feature=youtu.be
/r/Python
https://redd.it/8gw3sg
https://www.youtube.com/watch?v=okIujaQCfOw&feature=youtu.be
/r/Python
https://redd.it/8gw3sg
YouTube
Python turtle graphics
A simple Square Spiral made with python turtle graphics.
Making your C library callable from Python by wrapping it with Cython
https://medium.com/@shamir.stav_83310/making-your-c-library-callable-from-python-by-wrapping-it-with-cython-b09db35012a3
/r/Python
https://redd.it/8gwjuk
https://medium.com/@shamir.stav_83310/making-your-c-library-callable-from-python-by-wrapping-it-with-cython-b09db35012a3
/r/Python
https://redd.it/8gwjuk
Medium
Making your C library callable from Python by wrapping it with Cython
This story can also be read in my blog.
Announcing PyTorch 1.0 for both research and production
https://code.facebook.com/posts/172423326753505/announcing-pytorch-1-0-for-both-research-and-production/
/r/Python
https://redd.it/8gwyp7
https://code.facebook.com/posts/172423326753505/announcing-pytorch-1-0-for-both-research-and-production/
/r/Python
https://redd.it/8gwyp7
Facebook Code
Announcing PyTorch 1.0 for both research and production
We're announcing the next version of our open source AI framework, PyTorch 1.0, which integrates capabilities from Caffe2 and ONNX to provide a fast path from AI research to production.
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
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
reddit
Can you test login in shell? • r/djangolearning
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...
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
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
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
reddit
HELP - I want to build Dropbox or Google Drive clone... • r/django
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,...
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
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
reddit
Undeclared variable with "dictionary" syntax does not... • r/Python
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...
Hello Qt for Python - Qt Blog
http://blog.qt.io/blog/2018/05/04/hello-qt-for-python/
/r/Python
https://redd.it/8gylqd
http://blog.qt.io/blog/2018/05/04/hello-qt-for-python/
/r/Python
https://redd.it/8gylqd
www.qt.io
Hello Qt for Python
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
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
reddit
Crypto trading bot think-tank: what indicators do you use? • r/pystats
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...
Hyperparameters tuning with Polyaxon
https://medium.com/polyaxon/hyperparameters-tuning-with-polyaxon-9403f8ea85be
/r/Python
https://redd.it/8gztcf
https://medium.com/polyaxon/hyperparameters-tuning-with-polyaxon-9403f8ea85be
/r/Python
https://redd.it/8gztcf
Medium
Hyperparameters tuning on Kubernetes with Polyaxon
hyperparameters tuning is very important concept in order to choose the optimal hyperparameters for a given algorithm, it is crucial for…
[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
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
GitHub
ModoUnreal/dopenet
dopenet - The ideal template to make websites in 2018!!!! (I'm kidding of course)
[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
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
GitHub
GitHub - tatobari/hx711py: HX711 Python Library for Raspberry Pi.
HX711 Python Library for Raspberry Pi. Contribute to tatobari/hx711py development by creating an account on GitHub.