Flask: Bootstrap live search not working through render_kw in SelectField - python

My Flask web application form has a drop-down box with the list of all countries in the world. However, it gets tedious for the user to scroll and find the appropriate country they're looking for. Therefore, I'm trying to apply 'data-live-search' in my select fields for easier user navigation.
However, I'm trying to figure out the place I'm going wrong as my 'data-live-search=true' in select field does not yield any search box.
My codes are as:
routes.py (Flask Form)
def country_list():
return [('Angola','Angola'),('Andorra','Andorra').....] #All the countries
class Main_Form(FlaskForm):
countryList = SelectField("Enter the Country:", validators=[DataRequired()], choices=country_list(), render_kw={"data-live-search":"true"})
mainform.html
<div class = "container">
<fieldset>
<form class="form-group row" action="" method="post" novalidate>
<div class = "form-group col-md-12">
{{ wtf.form_field(form.countryList, class='form-control') }}
</div>
</form>
</fieldset>
</div>
When I look at the page source the data-live-search='true' appears for the select field but the drop-down does not contain any Search Box

Related

Can someone explain why my form fields are dissappering when they are not being selected?

Image of Form Fields Dissapeering When Not Selected
Hi all,
I am having trouble understanding why my fields are disappearing when they are not selected. I am rendering this form using Crispy Forms (followed via Youtube Tutorial). This feature was working earlier - however, I am not sure why it suddenly stopped working. I have a few other forms in this application and they are facing the same issue.
Here is the relevant code that is being used to generate the form
class BookAppointmentForm(forms.ModelForm):
class Meta:
model = BooksAppt
fields = '__all__'
labels = {
'hp_username': 'Doctor',
'appt_date': 'Appointment Date',
'p_username': 'Patients'
}
widgets = {
'appt_date': forms.TextInput(attrs={'type': 'date'})
}
def __init__(self, p_username=None, *args, **kwargs):
super(BookAppointmentForm, self).__init__(*args, **kwargs)
if p_username:
self.fields['p_username'].queryset = Patient.objects.filter(
p_username=p_username).values_list('p_username', flat=True)
Relevant HTML being used to render the form
<div class="container" style="background-color:#E6E6FA">
<div class="col-md-10 offset-md-1 mt-5">
<div class="card-body">
<h1 class="display-5 "> Booking an Appointment for {{ user }}</h1>
<p class="lead">Please Fill in the Following Form to Register an Appointment</p>
<hr class="my-4">
<form class="register" action="" method="post" autocomplete="off">
{% csrf_token %}
{{ form.errors }}
{{ form.non_field_errors }}
{{ form.p_username|as_crispy_field}}
{{ form.hp_username|as_crispy_field }}
{{ form.appt_date|as_crispy_field }}
<button type="submit" class="btn btn-success">Submit</button>
</form>
<br>
</div>
</div>
I feel as though the issue is something related to the bootstrap template I am using not playing nicely with crispy forms. I don't need a complete answer - just something to nudge me in the right direction. Please let me know if there is any other relevant information you need to help debug.
Thanks,
Shwinster
The issue was seen as a result of the bootstrap template. It was setting the text to white when not in focus. I was able to figure this out using inspect element and trying to see what stylistic properties were being set the form element.

Get the details of selected item

I have a part table and delivery instruction table (dins). To create a dins, I have to choose a part name. So what I want to do is, after choosing the part name from the dropdown that part's price will be visible in the form.
In the Part table, I have the price value for the specific part name. So during the creation of dins, after choosing such an example part name is X, then the form should show what is the price of that chosen part (X part) price.
Any idea how to make that happen?
views.py
def create_deliveryins(request):
from django import forms
form = DeliveryInsForm()
if request.method == 'POST':
forms = DeliveryInsForm(request.POST)
if forms.is_valid():
product = forms.cleaned_data['product']
usage = forms.cleaned_data['usage']
part= forms.cleaned_data['part']
deliveryins = DeliveryIns.objects.create(
usage=usage,
product=product,
part=part,
)
return redirect('dins-list')
context = {
'form': form
}
return render(request, 'store/addDins.html', context)
HTML
<form action="#" method="post" novalidate="novalidate">
{% csrf_token %}
<div class="form-group">
<label for="product" class="control-label mb-1">Product</label>
{{ form.product }}
</div>
<div class="form-group">
<label for="part" class="control-label mb-1">Part</label>
{{ form.part}}
</div>
<div class="form-group">
<label for="usage" class="control-label mb-1">Usage</label>
{{ form.usage }}
</div>
</form>
Create a hidden form field that has the part prices for each part.
Use Javascript or Jquery to update the form field for price and show it whenever the form part field is changed.
This would prevent the need for ajax, or additional views or requests.
You would only need to slightly modify your view and template.

Displaying multiple flask variables from different forms at once in HTML template

I have 2 separate forms on a html template called queries.html, one for inputting a company name and one for inputting keywords as seen below.
<form method="POST">
<p>Enter Company Name:</p>
<p><input type="text" name="company_name"></p>
<p><input type="submit" value="submit"></p>
</form>
<p> Name: {{ name }} </p>
<form method="POST">
<p>Enter Keywords:</p>
<p><input type="text" name="keywords"></p>
<p><input type="submit" value="submit"></p>
</form>
<p> Keywords: {{ keywords }}</p>
I want to be able to display the form input in the paragraph tags seen below each form.
Below is the relevant flask code:
#app.route('/queries/', methods=['GET', 'POST'])
def queries():
if request.method == 'POST':
if request.form['company_name']:
name = request.form['company_name']
return render_template('queries.html', name=name)
elif request.form['keywords']:
keywords = request.form['keywords']
return render_template('queries.html', keywords=keywords)
return render_template('queries.html')
My problems are, firstly, the company name when entered does display fine where the {{ name }} element is as it should but when inputting a keyword I get a 'bad request' error. Secondly, I did previously have both inputs working but when I would use one form, it would wipe the displayed data from the other, e.g. when inputting a keyword after having already input and displayed a company name, the keyword would appear at the {{ keyword }} element as it should but the company name would disappear. After some research I may need to use AJAX to keep the all elements displayed but not sure if i'm looking in the right direction. It seems this should be a relatively simple issue to solve, please help! Thanks in advance to any responses.
In Place of :
request.form['company_name']
request.form['keywords']
Use this :
request.form.get("company_name")
request.form.get("keywords")
Flask throws error if there is no value in the form input. Using form.get the flask will try to get the value and will handle if there is no value.

Django - Conditional Rendering In Templates

I need some help conditionally rendering data in a modal pop up window on my site.
What I want to do:
When the user clicks on the "make reservation" button, I want to display this in the modal window
<h3 style="margin-top:20px;">Choose dates</h3>
<div style="margin-top:20px;" class="pick-dates-div">
<form method="GET" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="form-btn save btn btn-default">Make A Reservation</button>
</form>
<button style="margin-top: 25px;" class="btn-primary btn-block btn-lg" data-toggle="modal"
data-target="#inquiryModal">More
Questions ?</button>
</div>
Then the user can pick the dates from the date picker and press the "make a reservation" button ( which is a GET request ), the page refreshes and I want to display only this in the same modal window :
<h1>Start Date: {{ date_start }}</h1>
<h1>End Date: {{ date_end }}</h1>
<h1>Price Per Day: ${{ price_per_day }}$</h1>
<h1>Total: ${{ total_price }}$</h1>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button href="www.facebook.com" type="submit" class="form-btn save btn btn-default">Confirm Reservation</button>
</form>
After that the user submits the form ( POST request ) and I want to display a text :
<h3> Thank you for your reservation </3>
What would be the ideal way to achieve this ?
Thank you stack
The ideal way to achieve this is by using JavaScript.
One of the many methods this could be achieved is by rendering all the three views inside separate containers in a modal and then hiding the next two using javascript.
You can use element.style.display = 'none' to hide and
element.style.display = 'block' to show the content inside the element container.
Once the user clicks on "make reservation" button, hide/show the required containers to achieve the desired result.
Do not forget to secure your website by using proper validation on the server end. Hope that helps!

Displaying custom checkboxes with Django and ManyToManyField

I'm having trouble wiring my checkboxes together with the template to make a good user experience. I'm sending my form to the view which contains the following MyType which is described as:
models
class A(models.Model):
MyType = models.ManyToManyField(P)
forms
MyType = forms.ModelMultipleChoiceField(queryset=P.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)
and the view is being sent as:
return render(request, "static/about.html", {'form': form})
and in the template, I have the following kind of structure
<li class="option table">
<div class="cell" id="center">
<div class="option-text">Option 1</div>
</div>
<div class="cell" id="right">
<div class="option-checkbox">
<div class="check"></div>
<input id="myid1" name="myname1" value="1" type="checkbox">
</div>
</div>
Now I can use answer: On a django form, how do I loop through individual options per field? to loop through, but this only gives the description. How do I recreate the actual HTML that deals with the options in the smartest way?
I've tried the shell to look at the objects, but I really don't see what I should be pulling in. i.e. in the template to recreate. What fields of each option should I pull in? or how do I get at the right info to build up my HTML such that the saving aspect of the form will work.
In a template I cannot do:
{% for field in form["MySmoking"] %}
{% endfor %}
so how could I modify the following:
{% for option in form.MyType.field.choices.queryset %}
{{ option.image }}
{{ option.title }}
{{ option.description }}
{% endfor %}
so, how would I spit out the HTML that builds the checkbox.
Thanks.

Categories

Resources