Populate html drop-down using data from postgresql database using Python-Flask - html

<html>
<head>
</head>
<body>
<form>
<select multiple="multiple"
<option value="Hello">Hello</option>
</select>
</form>
</body>
</html>
I am using postgresql database in which I have table with one column and one row saying 'Hello'
I want to pull that data and display it as selection option in html form using FLASK.
Can anyone help me please,
Thanks in advance

It seems like you need to read Flask's Quickstart to learn some basic.
Here is a minimal application that meets your needs.
View function:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
items = get_your_data_from_db()
return render_template('index.html', items=items)
templates/index.html
<html>
<head>
</head>
<body>
<form>
<select multiple="multiple">
{% for item in items %}
<option value="{{ item.field_name }}">{{ item.field_name }}</option>
{% endfor %}
</select>
</form>
</body>
</html>

Related

Are "required" HTML fields not enforced on Django Admin intermediate pages?

I have the following abbreviated HTML for an intermediate Django admin page:
<!DOCTYPE html>
{% extends base_url %}
{% block content %}
<form action="" method="post">
...
<select name="my_name" id="my_id" required>
<option disabled selected> --- </option> <br />
...
</select>
...
<input type="hidden" name="action" value="my_action" />
<input type="submit" name="apply" value="Update" />
</form>
{% endblock %}
However, my required attribute does not seem to work, and clicking "Update" submits the form even if no selection has been made.
Am I missing something special about how Django builds intermediate pages?
Happy to provide more code if needed, just removed most of it and replaced with ... for brevity's sake.
Edit: I was able to sidestep the issue by raising an error message if my field wasn't filled out, but that seems messier since it kicks the user back to the Admin page each time:
is_valid_form = 'my_id' in request.POST
if not is_valid_form:
fail_message = (
"Error: All fields are required.")
admin_page.message_user(
request, fail_message, messages.ERROR)
return HttpResponseRedirect(request.get_full_path())

Django: get drop-down values for a FormField

Aim is to get the drop-down to work.
Normally no problems when feeding the whole Model / ModelForm into the html template as {{ form }}
Below html code snippet is my aim, but instead of {{ form }}, I would like to feed the subset {{ form.car_model_make }} and let Django automatically create all Options <option value="BWM">BMW</option> ... etc
# models.py
class Product(models.Models):
car_model_make = models.CharField(default='B', max_length=1, blank=True, choices=CAR_TYPE)
status_is_secondhand = models.BooleanField(blank=True)
# forms.py
class ProductForm(ModelForm):
class Meta:
model = Product
fields = ('__all__')
# views.py
class ProductFormView(FormView):
form_class = ProductForm
def form_valid(self, form):
form.save()
return super().form_valid(form)
def get_success_url(self):
return reverse('index')
# urls.py
urlpatterns = [
path('', index, name='index'),
path('product/', ProductFormView.as_view(template_name='product/product.html'), name='product'),
]
The choices CAR_TYPE is a list containing "BMW, Mercedes, Audi".
Trying to achieve this:
When I replace:
<option value="BWM">BWM</option>
<option value="Mercedes">Mercedes</option>
<option value="Audi">Audi</option>
in the HTML code snippet below
with
{{ form.car_model_make }}
I get "No results found"
with
<option> {{ form.car_model_make }} </option>
I get a list of the choices (BMW, Mercedes, Audi) but they are not selectable
However, with
<option {{ form.car_model_make }} </option>
It works but I get a warning Tag start is not closed. If I close the Tag, I get the tag character ">" also printed in the drop down.
same result is produced for: <option value=" {{ form.car_model_make }} "></option>
I am in the dark and the trial and error does not give me the desired solution. How do I do it?
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>
<body>
<div class="container">
<div class="col-sm-12 mg-t-10 mg-sm-t-0">
<select class="form-control select2"
style="width: 100%;"
data-placeholder="Choose Car Make"
>
<option value="BWM">BWM</option>
<option value="Mercedes">Mercedes</option>
<option value="Audi">Audi</option>
</select>
</div>
</div>
</body>
</html>
It seems like there are two steps to get what you are looking for.
Get the select to show up:
instead of replacing the options, replace the entire select with {{ form.car_model_make }}
Custom formatting for the widget:
Following Django's ModelForm documentation you can override the widget to customize the look and feel, something similar to the following:
widgets = {
'car_model_make': Select(attrs={
'class':"form-control select2",
'style':"width: 100%;",
'data-placeholder':"Choose Car Make"}),
}

Error retrieving multiple select option in Django

I have a drop down with multiple select option in my html page. On form submission, I am trying to capture all of the selected options by user in that drop down. but it throws me an error instead "TypeError:'instancemethod' object is not subscriptable". Following is my template.html and views.py
Template.html:
Select packages:
<form name=automationForm action="/vsawebauto/automation/results/" method="post">
//some form elements
<select id="package" name="package[]" multiple="multiple" size="5">
{% for i in ida.package_set.all %}
<option value="{{ i.pkg_id }}">{{ i.display_name }}</option>
{% endfor %}
</select>
//some form elements
<input type="submit" id="submit" value="Submit Job" />
Views.py:
def results(request):
//some code
selected_packages = request.POST.getlist['package[]']
//some code
return HttpResponse("Selected Packages:"+selected_packages)
Note: I debugged the code as well. The request.POST object has multiple selected values. For eg. when 1 and 701 packages are selected by user, request.POST has 'package[]': ['1','701']. But the code fails when I do request.POST.getlist['package[]']
request.POST.getlist['package[]']
Should be
request.POST.getlist('package[]')
Replace [] with () which was the cause of the error.
Here is the documentation and usage of getlist.
Also, change
return HttpResponse("Selected Packages:"+selected_packages)
to
return HttpResponse("Selected Packages: %s" % selected_packages)

dropdown menu html code with select options from django

My HTML code is below:
<select name="txn" tabindex="3" id="txn" class="fixed" onfocus="highlightInput(this.id)" onblur="unhighlightInput(this.id)">
<option value="RR" my="{{txn|genselected:"RR"|safe}>RR</option>
<option value="CR" my="{{txn|genselected:"CR"|safe}}">CR</option>
<option value="SR" my="{{txn|genselected:"SR"|safe}}">SR</option>
<option value="OR" my="{{txn|genselected:"OR"|safe}}">OR</option>
</select>
txn is defined in forms.py as:
txn = forms.ChoiceField(label="txn", choices = it_const.TXN),
My Question:
The option values are dynamically increasing in the database? i Want to read the option values from the database and put them in dropdown menu in html. Can you please help me with HTML code and how to read the options from txn form field and display it in menu options.
Thanks in advance.
views
def view_name(request):
form = OptionForm()
options = Option.objects.filter()
return render(request, 'page.html', {
'form': form,
'options': options,
})
html
<form method="post">
{% csrf_token %}
{{form}}
<input type="submit" value="Submit">
</form>
{% for option in options %}
<p>{{option.field}}</p>
{% endfor %}
You can retrieve the database values in the view file, and then add them to an array, and then render the array as option for form field.
TXN_choices = Options.objects.all()
#and then run a for loop to dynamically generate the options array:
TXN = (
('x', 'xxx'),
('y', 'yyyy'),
)
and then render the ModelForm.

How to loop use jinja2 for loop to create a select element?

Say I have a python list called seq and I want to render it in a select element how do I do that?
I tried:
<select name="Exercise1">
{% for item in seq %}
<option value="{{item}}">{{item}}</option>
{% endfor %}
</select>
it didn't work.
UPDATE:
here is the template code:
<!DOCTYPE html>
<html>
<head>
<title>Unit 2 Rot 13</title>
</head>
<body>
<h2>Enter some text to ROT13:</h2>
<form method="post">
<select name="Exercise1">
{% for item in seq %}
<option value="{{item}}">{{item}}</option>
{% endfor %}
</select>
<br>
<input type="submit">
</form>
</body>
</html>
and here is the rendered html source code:
<!DOCTYPE html>
<html>
<head>
<title>Unit 2 Rot 13</title>
</head>
<body>
<h2>Enter some text to ROT13:</h2>
<form method="post">
<select name="Exercise1">
</select>
<br>
<input type="submit">
</form>
</body>
</html>
I'm not sure why the element just disappears and there is no errors raised.
You are very close my friend you just missed a few spaces:
You wrote this:
<option value="{{item}}">{{item}}</option>
Which needs to look like this:
<option value="{{ item }}">{{ item }}</option>
Let me know if that fixes it. Good luck!
Without those spaces it just looks like garbage to python and to the browser :)
Check the function where you render template, it must contain:
def generate_template_for_exercize1():
seq = [1, 2, 3] #here you probably will have more complex statement
return render_template('your_template.html', seq=seq)