dropdown menu html code with select options from django - html

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.

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())

Dynamically change values based on user selected option django

I'm trying to change a value based on the exchange rate selected by the user within the <option> tag. I don't want to save the form result to the database. I just want it to dynamically change whenever the user changes the currency option.
Say a user selects a currency from the below form with the options in the view:
VIEW
def view(request):
currency_dict = {'EUR': 0.9154994049253867, 'JPY': 123.86706948640484, 'BGN': 1.7905337361530713, 'CZK': 22.375720955781375}
cur = currency_dict.items()
deposit = 10000
context = {
'currency_dict': currency_dict,
'cur': cur,
'deposit': deposit,
}
return render(request, 'coinprices/my-dashboard.html', context)
HTML - FORM
<div class="container">
<div>
<span>
<h1>My Dashboard</h1>
</span>
<span>
<form method="post">
<label>Choose Currency:</label>
<input list="ex-currency">
<datalist id="ex-currency">
{% for k, v in currency %}
<option value="{{ k }}"></option>
{% endfor %}
</datalist>
{% csrf_token %}
<button class="btn btn-outline-success btn-sm">Submit</button>
</form>
</span>
</div>
</div>
Then based on the users selection, multiply the {{ deposit }} value by the currency_dict[user_selected_currency] and change the bold text (see below):
DESIRED OUTCOME
<span>
<div><b>Total Investment {{ user_selected_currency }}</b></div>
<span class="text-xl">${{ deposit * currency_dict[user_selected_currency] }}</span>
</span>
Any ideas how this can be achieved?
Unfortunately, this is not a thing you can do with the render function you will need a GET request using ajax when the user changes the value, and then you can call a function based on the user option and return a valid response to the user this called "Chained Dropdown List" I found this amazing article that maybe can help you How to Implement Dependent/Chained Dropdown List with Django

HTML form - only works on a single button in a loop

So I am creating a table with a form and I have 2 rows the problem is the submit button works only on one button and the second submit it does the form but doesn't send any values
<tr>
{% for(username, computer_mac, assign_value) in zip(users_username, computers_mac, assigned_values) %}
<form action="" method="POST">
<td>
computer number:
<select class="custom-select" name={{username}}>
{% for client_id in computer_client_id%}
<option value={{client_id}} name={{client_id}} >{{client_id}}</option>
{% endfor %}
<option value="-1" name="-1">None</option>
<option hidden selected>{{assign_value}}</option>
</select>
</td>
<td>{{username}} ({{computer_mac}})</td>
<td class="assigned_values">{{assign_value}}</td>
<td>
<input type="submit" class="btn btn-danger btn-md a" id="button-id" value="submit">
</td>
<td>
<div id="status"></div>
</td>
</form>
</tr>
{% endfor %}
{{username}} = Raz
{{client_id}} = 1
{{other_username}} = a
{{other_client_id}} = None
in the first button, I can see that it "{{username}}={{client_id}}&{{other_username}}={{other_client_id}}" what I'd like to have is for every button it'd be separate so the first button will have his {{username}}={{client_id}} and the second button would have his {{other_username}}={{other_client_id}} how do I do it?
JS data send:
var data = $("form").serialize();
console.log(data);
$.ajax({
type: "POST",
url: 'admin/data',
data: data,
So I solved it the first problem was that I needed to create a class for the button so it will work on multiple buttons instead of 1:
so simply adding to the button class: "button-class" and delete the id
now the problem is that for both of the buttons the form output is this Raz=1&a=None which could be good for you but I wanted them separate so
button 1 - Raz=1
button 2 - a=None
so what I did is that I found the index of the button that I am clicking on
var currentIndex = $('.button-class').index(this);
and simply split at &
try{
data = data.split('&');
data = data[currentIndex]
}
catch(err){
data = ""
}
and that's it now I have the right info for the different buttons.

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

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

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)