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)
Related
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())
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
The project have url as follows,
path('post/<str:state>/',SearchView.as_view(),name='search-data')
I have a HTML form, upon filling and submitting it supposed to pass filled form data to URL.
<form action={% url 'search-data'%} method="get" >
{% csrf_token %}
<input type="text" name="fname">
But it does not work as supposed to be.
When form submitted it gives below URL
http://127.0.0.1:8000/%7Burl?csrfmiddlewaretoken=2RZfZ4cxLB...
You don't have to pass <str:state> argument in your urlpatterns just pass path('post/search',SearchView.as_view(),name='search-data') or whatever you want but problem is when you pass an argument like this post/<str:state>/ than you have to specify that in your form action also
like this {% url 'search-data' state %} initialy you don't have any state so that's why you have to get the state name from your form so finnaly your code look like this
<form action={% url 'search-data'%} method="get" >
{% csrf_token %}
<input type="text" name="fname">
<input type="submit" value="search">
</form>
and than in your views you've to get it from request.GET method like this
def search(request):
state = request.GET.get('fname', None)
.... do whatever you want
return response_or_data
I got variable myvar in my wtf-form.
I would like to set it's value upon the user selects an option in the dropdown list, w/o the need to add a button/input for the user to confirm his selection.
So far, I am not able to have a POST event triggered in views.py whenever the user selects an option.
Moreover, setting form.myvar as I do below doesn't actually do anything, and the alert message won't fire either.
My flask template code:
<!-- extend base layout -->
{% extends "base.html" %}
<script>
$('#sel_id').change(function() {
window.alert(5 + 6);
});
</script>
{% block content %}
<div>
<form action="{{ url_for('compile') }}" method="POST">
<dl>
<select id="sel_id">
<option value="1">1</option>
<option value="2">2</option>
</select>
</dl>
</form>
</div>
<script type=text/javascript src="{{
url_for('static', filename='jquery.js') }}"></script>
{% endblock %}
I would write a piece of JavaScript or jQuery to handle this.
$('#sel_id').change(function() {
var = 4;
});
Also, you will want to name your variables something other than var, which is keyword. Name it something more descriptive.
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.