I want to render the options for a ModelChoiceField:
{% for value, label in form.fields.event_type.choices %}
<option value="{{ value }}"
{% if form.fields.event_type.value == value %}selected="selected"{% endif %}>
{{ label }} -- {{ form.event_type.value }} .. {{ value }}
</option>
{% endfor %}
But this does not work: selected="selected" is not set.
The output:
<option value="">
--------- -- 2 ..
</option>
<option value="1">
OptionOne -- 2 .. 1
</option>
<option value="2">
OptionTwo -- 2 .. 2
</option>
This is strange, since the output "2 .. 2" did not trigger the "if" to include selected.
How to solve this?
I found the solution. The "if" was comparing an integer to a string, which is not equal.
This works:
{% for value, label in form.fields.event_type.choices %}
<option value="{{ value }}"
{% if form.event_type.value == value|stringformat:"i" %}selected="selected"{% endif %}>
{{ label }} -- {{ form.event_type.value }} .. {{ value }}
</option>
{% endfor %}
i have table in db in which i stores countries and i dynamically pass those countries in template and and in forms.pt i have a ChoiceField(widget=forms.Select,required=True) like this but i didnot get the value from this filed but when i chane it into CharField i get the value.
<div class="form-group col-md-4 select-border">
<label>Country</label>
<select class="form-control basic-select" name="country">
{% for country in countries %}
<option value="{{ country.value }}">{{ country.value }}</option>
{% endfor %}
</select>
</div>
form.py
country = forms.ChoiceField(widget=forms.Select,required=True)
views.py
users_meta.candidate_country = ProfileForm.cleaned_data['country']
I am having problem to get the selected data from a form. Here is my form
<form action="#" method="GET">
{% csrf_token %}
<select name="country" id="selectcountries" class="custom-select">
<option>Select country</option>
{% for item in countries %}
<option val="{{ item.name }}"> {{ item.name }} </option>
{% endfor %}
</select>
<select name ="city" id="selectcities" class="custom-select">
<option>Select city</option>
</select>
<select class="custom-select" name="option" >
<option selected> Tourist Spot </option>
<option> Hotel </option>
<option> Restaurent </option>
</select>
<button type="submit" class="btn tour-btn"><i class="fa fa-search pr-2" aria-hidden="true"></i> Search </button>
</form>
And my views.py is
def advanceSearch(request):
country = request.GET.get('country')
city = request.GET.get('city')
option = request.GET.get('option')
if request.method == "GET" :
if country:
message = 'q= %s' % country
else:
message = 'Empty'
else:
message = 'oops'
return HttpResponse(message)
HTTPResponse always give me empty message even after with passing values by the form. I want to get the data from this form but i cant.
I tried to replicate the scenario with the provided code, and I think your search view is not getting executed. You have provided {% url 'advanceSearch' %} in the anchor tag inside button. It should be in the action attribute of the form.
<form action="{% url 'advanceSearch' %}" method="GET">
{% csrf_token %}
<select name="country" id="selectcountries" class="custom-select">
<option>Select country</option>
{% for item in countries %}
<option val="{{ item.name }}"> {{ item.name }} </option>
{% endfor %}
</select>
<select name ="city" id="selectcities" class="custom-select">
<option>Select city</option>
</select>
<select class="custom-select" name="option" >
<option selected> Tourist Spot </option>
<option> Hotel </option>
<option> Restaurent </option>
</select>
<button type="submit" class="btn tour-btn"><i class="fa fa-search pr-2" aria-hidden="true"></i>Search</button>
</form>
I am using a database "selectCountry" and I want to select all the country names in the database to get populated in the html dropdown menu.
Following is my code
models.py
class selectCountry(models.Model):
selectCountryoption = models.CharField(max_length = 30)
views.py
def loadCountries(request):
countries = selectCountry.objects.all()
return render(request, 'register/bg-pages.html', {'countries':
countries})
html code
<form action=".">
<select name="Country" id="searchOption">
<option value="">---------</option>
{% for country in countries %}
<option value="{{ countries.selectCountryoption }}">{{
countries.selectCountryoption }}</option>
{% endfor %}
</select>
<input type="submit" value="submit" name="submit"
</form>
</p>
The problem is the values are not getting populated in the list when I am requesting the page.
You are using the wrong value in your for loop.
<option value="{{ countries.selectCountryoption }}">{{
countries.selectCountryoption }}</option>
should be
<option value="{{ country.selectCountryoption }}">{{
country.selectCountryoption }}</option>
I have a select field in the form and now I need to iterate over options in this field.
{{ form.myselect }} gives me this:
<select name="myselect" id="id_myselect">
<option value="" selected="selected">---------</option>
<option value="2">Item 1</option>
<option value="3">Item 2</option>
...
</select>
Now I need to add some attributes to the options and because of that what I need is:
<select name="myselect" id="id_myselect">
{% for x in form.myselect %}
<option value="{{ x.id }}">{{ x.name }}</option>
{% endfor %}
</select>
but there is an error:
Caught TypeError while rendering: 'BoundField' object is not iterable
I tried form.myselect.all, form.myselect.option_set but it gives nothing
I've been struggling with this problem today and found the solution. Yes, you can iterate over options of the select tag directly in template. Here's how to do it in template:
<select id="id_customer" name="customer">
{% for x, y in form.fields.customer.choices %}
<option value="{{ x }}"{% if form.fields.customer.value == x %} selected{% endif %}>{{ y }}</option>
{% endfor %}
</select>
In this case I have a customer field in the form which has choices set up as follows:
class SomeForm(forms.Form):
customer = forms.ChoiceField(label=u'Customer')
def __init__(self, *args, **kwargs):
super(SomeForm, self).__init__(*args, **kwargs)
self.fields['customer'].choices = [(e.id, e.customer) for e in Customers.objects.all()]
Got it to work with:
<select name="myselect" class="i-can-add-my-own-attrs-now" id="id_myselect">
{% for id, name in form.myselect.field.choices %}
<option value="{{ id }}">{{ name }}</option>
{% endfor %}
</select>
BUT REALLY, a better way to do this is with django-widget-tweaks:
{% load widget_tweaks %}
{{ form.myselect|add_class:"i-can-haz-custom-classes-easily" }}
Doing it with django-widget-tweaks will also set the default 'selected="selected"' for you, which is super nice!
I do this way:
<select id="id_construction_type" name="construction_type" class="form-control input-md">
{% for value, key in form_urban.fields.construction_type.choices %}
<option value="{{ value }}"{% if form_urban.initial.construction_type == value %} selected {% endif %}>
{{ key }}
</option>
{% endfor %}
</select>
This is a cleaner solution, you can set the attributes using a custom Widget. This way you don't have to render the field manually:
class CustomSelectWidget(forms.Select):
def create_option(self, name, value, *args, **kwargs):
option = super().create_option(name, value, *args, **kwargs)
if value:
instance = self.choices.queryset.get(pk=value) # get instance
option['attrs']['custom_attr'] = instance.field_name # set option attribute
return option
class SomeForm(forms.ModelForm):
some_field = forms.ModelChoiceField(
queryset=SomeModel.objects.all(),
widget=CustomSelectWidget
)
With radio buttons in your template use.
<table>
{% for x,y in form.fields.Customer.choices %}
<tr>
<td><input id="id_Customer_{{x}}" {% if form.fields.Customer.value == x %}checked="checked"{% endif %} name="Customer" type="radio" value="{{x}}" /></td>
<td>{{ y }}</td>
</tr>
{% endfor %}
</table>