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
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%}
<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