Python & Flask HTML - Making n number of textboxes based on variable - python

I have a flask webpage I am trying to create. When users register for an account, they declare the number of agricultural fields they have. This is saved in a MySQL database. From this, I need users to add information on another input page. This input page should have "n" number of textboxes based on the number of fields they have.
Is there anyway to create "n" number of textboxes in HTML? I can read in the number of fields from their account but cannot find a way to create a variable number of textboxes within HTML.
I do not need this to be dynamic (the user add or remove) this needs to be a FIXED amount of textboxes.

I'm going to assume that because of flask you are using jina2 as your rendering engine, let's call the number of fields that need to be created n, you can just use the loop structure
{% for i in range(n) %}
<input name="field-{{i}}" />
{% endfor %}
you can get more info at https://jinja.palletsprojects.com/en/3.0.x/templates/#for
if you need more complex forms, I would recommend using WTForms.

Found a solution, it is a little ugly but should work.
in your html:
<table>
{% for x in range(fields | int) %}
<tr>
<td>
<input type="text" value="{{ x }}">
</td>
</tr>
{% endfor %}
</table>
in python:
def irrigation_input():
...... non important stuff here.....
fields=account_info_irr[9]
int(float(fields))
return render_template('irrigationinput.html',fields=fields)

Related

Python Django: Get what input field the cursor is in?

I am relatively new to Django and don’t have a lot of experience with python.
So far I display some input fields this way, where I'm looping through a range and then making the equivalent amount of fields. But is there some way to know which field is active, like what field is the cursor in?
The reason for why I want to know what field is active is because I have created a list with a bunch of special symbols, like math symbols and Greek letters, which the user can click, I then want the active field to display the clicked symbol. hope it makes sense
I was made aware of something called focus but I don’t think I understand how to use it. If someone could explain it would be great
This is the "important" part of my .html file
{% with ''|center:number_of_variables as range %}
{% for i in range %}
<input type="text" name="know_variable_description{{ forloop.counter0}}" placeholder="Symbol" >
<input type="text" name="know_variable_symbol{{ forloop.counter0}}" placeholder="Name" >
{{ forloop.counter0}}
{% endfor %}
{% endwith %}
in the input field, you can use the onfocus event
<input type="text" onfocus="myFunction()" name="know_variable_description{{ forloop.counter0}}" placeholder="Symbol" >
The onfocus event will call the function myFunction whenever the input is focused(active), and you can put your other logic in the function myFunction in javascript.

CBV: How To Make A Drop Down Database Query Using Django FormView

What I would like to do is have a dropdown list containing objects from a database. When the user selects an object, I would like the information displayed on the page.
What I have been able to do is have the values shown in the dropdown list, but I have not been able to display the way I'd like. I've been trying to do so a certain way to hopefully be able to better control the look of the form.
models.py
class Vehicle(models.Model):
make = models.CharField(max_length=20)
model = models.CharField(max_length=20)
def __str__(self):
return self.make + ' ' + self.model
class Package(models.Model):
make_model = models.ForeignKey(
Vehicle, on_delete=models.CASCADE
)
name = models.CharField(max_length=20)
price = models.IntegerField()
views.py
class VehicleCompareView(FormView):
template_name = "main/somehtml.html"
form_class = forms.CompareForm
forms.py
objectlist = forms.ModelChoiceField(queryset=models.Package.objects.all() \
.order_by('make_model__make'))
html file
<form method="GET">
<select class="form-control">
<option value="0" selected disabled>Select Vehicle 1</option>
{% for q in form.objectlist %}
<option value="{{q.name}}">{{ q.make_model__make }}</option>
{% endfor %}
</select>
</form>
<div>
<p>Selected Vehicle: {{q.make_model__make}} {{q.make_model__model}}<br>
Price: ${{q.price}}
</p>
</div>
So let's start with what I have found that somewhat works from messing with the code.
If I use {{form}}, I get the package list, but it only displays the package name of course. If I attempt to use .values() in the query set in forms.py, it returns what I want, but in a dictionary(so it'll literally show 'make': 'someMake', 'model':'someModel', 'package:'somepackage') in the user dropdown list.
When I attempt to do the select/option way that I prefer to, after the for loop doing {{ q }} returns the same list of packages, but if I try to format what I want to see {{ q.make_model__make }} {{ q.make_model__model }} {{q.name}}, nothing shows except a dropdown of blanks(though the correct number of blanks).
There may be a better way than what I'm trying, but from a lot of searching and looking around on here I found my way to using a FormView with a ModelChoiceField query set. At the end of the day, I want a dropdown list to show Make Model Name from the database. When the user makes a selection, I would like to display the attributes on the page. Obviously I haven't even gotten to the issue of the selection part yet. From what I understand I'll need to use Ajax to have everything populate on selection. But that's a problem for another time. For now I'd just like the dropdown to display the way I'd like. Preferably using the select/option method so I can have control over the look rather than just rendering a generic form.
I solved my issue. I started reading all posts on Django query forms I could find, including those that didn't relate to my issue, to better understand exactly how everything works. Someone mentioned that the select statement is built inside the ModelForm. I then realized I was trying to force two different things, and why what I was doing didn't really make sense. I played with the code some more and here is what I did to solve my issue of displaying in the manner I wanted.
forms.py
objectlist = forms.queryset = models.Vehicle.objects.all().order_by('make')
html
<form>
<select class="form-control">
<option value="" selected disabled>Select Vehcile 1</option>
{% for q in form.objectlist %}
{% for b in q.package_set.all %}
<option value="">
{{ q.make }} {{ q.model }} {{ b.name }}
</option>
{% endfor %}
{% endfor %}
</select>
</form>
Using the nested for loop was the only way I could get the attributes of a related model to display inside the same select dropdown. The model Package has a foreign key called 'make_model' that refers to the model Vehicle. I wasn't able to call 'make_model__make' to display related vehicle names with the package in the dropdown list.
I'll leave my mistake up for anyone else having a similar issue to see what not to do in this situation along with what worked for me in the end.

save dictionary to database from html template in flask

I will try my best to be as concise as possible.
In my back end, I have a list of dictionaries saved to a variable. Each dictionary represents a post from reddit and includes the score, url, and title.
Respectively, the template will loop through this list and then return the values of each of these keys to the user like so:
<table>
<tr>
{% for x in data[0:5] %}
<td>
{{ x['score'] }}
{{ x['title'] }}
<br>
<a href='/add_to_favorites'> Add To Favorites </a>
</td>
{% endfor %}
</tr>
</table>
As you can see, there's an tag which is linked to a function on my utils.py that is attempting to save the respective dictionary to the database (I have a model that represents the url, title, and score).
I feel as though my template is not representing the dictionary in the correct way, for my link to include the html as when it is pressed I receive a 404 error (though I have this route already defined in views.py - '/add_to_favorites' which calls my 'save_post' function).
def save_post():
data = get_info()
for post in data:
fav= Favorite(title=post.get('title'), url=post.get('url'), score=post.get('score'), user_id=current_user.id)
db.session.add(fav)
db.session.commit()
return redirect(url_for('favorites'))
and:
#app.route('/add_to_favorites')
#login_required
def add_to_favorites():
return save_post()
Am i going about this the wrong way? How can i make sure that the link/button is associated with only the html of the that it is included in?
Just need some guidance into the right direction here, not necessarily the code to fix it. Thank you

Creating variable numbers of text boxes using Python Flask?

My website has a search bar, and it takes in a search query. Depending on the length of the query (number of characters, for example), I want to create more or less text boxes, for a maximum of 10. (The total number doesn't really matter -- I just don't know how to make a variable number of text boxes in general.) Thus, what would be the best way to do this?
#app.route('/searchQuery', methods=['POST'])
def searchQuery():
searchquery = request.form['searchQuery']
print searchquery
searchquery += " || python added this line!"
return render_template('simplesearch.html', content=searchquery)
<div><center>{{content}}</center></div>
However, if I want to create new divs for up to 10 unique items, what would be the best way to do this?
Okay,
So a basic example of what you are trying to do. Note: this is quick code but should lead you in the right direction:
your_file.py
#app.route('/')
def index():
return render_template('index.html')
#app.route('/searchQuery', methods=['POST'])
def search_query():
sq_ = request.form.get('searchQuery')
print(sq_)
return render_template('simplesearch.html', search_query=sq_)
index.html
<form action="{{ url_for('search_query') }}" method="post">
<input type="text" name="searchQuery" id="searchQuery"><input type="submit" value="Submit">
</form>
simplesearch.html
<table>
{% for x in range(search_query | int) %}
<tr>
<td>
<input type="text" value="{{ x }}">
</td>
</tr>
{% endfor %}
</table>
Basically you are going to capture the "number" that you pass in. I would suggest putting in some checks. Then use Jinja to render the text boxes. Which you can then post to a new page or do whatever with it.

How do I submit multiple forms with a single submit button in django?

I have managed to create the forms I need using modelformset_factory.
avaluos = Avaluo.objects.filter(Estatus__contains='CONCLUIDO',Factura__isnull=True)
FacturaFormset = modelformset_factory(Avaluo,form=FacturaForm,extra=0)
Currently this is generating the following HTML for each of the rows found:
<form id="id-FacturaForm" class="blueForms" method="post">[..]</form>
<form id="id-FacturaForm" class="blueForms" method="post">[..]</form>
<form id="id-FacturaForm" class="blueForms" method="post">[..]</form>
I want to submit all the forms using a single submit button.
Any ideas?
UPDATE
I ended up using django-crispy-forms which allowed me to gerate inputs for each row, and then I just manually added the form and submit.
self.helper.form_tag = False
{{example_formset.management_form }}
{% for a,b in olist %}
{{ b.id }}
<tr>
<td style="width:10px;"> {% crispy b %} </td>
<td> {{a.id}} </td>
</tr>
{% endfor %}
Read more into model formsets. You don't need to have separate form tags, it's the whole point of using a formset.
<form method="post" action="">
{{ factura_formset.management_form }}
<table>
{% for form in factura_formset %}
{{ form }}
{% endfor %}
</table>
</form>
Also, every time you use the id attribute more than once on a page… a developer cries themselves to sleep somewhere in the world.
I suspect you will need to do it using Ajax - otherwise as soon as one form is submitted you will not be able to go the other way.
There are a few jQuery form libraries that should make it relatively straightforward. For example, http://malsup.com/jquery/form/.
It would look something like:
$('#button-id').click(function() {
$('.blueForms').ajaxSubmit();
});
Of course, you'll then need to deal with error handling and waiting for all the forms to have submitted.
If you're trying to create many instances of the "same" form (this is, they all look equal), as if it were one of many childs belonging to a single, master element, you don't actually need to create a form tag for each of the formsets.
If I'm not mistaken, you're trying to edit many facturas for a single avaluo object. Am I right? The representation would be a single "avaluo" form with many inline formsets, one for each "factura".
Check out the inline formsets factory instead of the modelformset factory.

Categories

Resources