show selected option when render posted form in django - html

I have tried to render a form with a ChoiceField like bellow :
<div class="col-25">
<label for="category">Subcategory</label>
</div>
<div class="col-75">
<select name="category" id="id_category">
{% for x in FilterbyCategory.fields.category.choices %}
<option value="{{ x.0 }}"{% if FilterbyCategory.fields.category.value == x.0 %}selected{% endif %}>
{{ x.1 }}
</option>
{% endfor %}
</select>
</div>
When I submit the form, I don't get the initial option selected.
DO I have a problem here ?
in the view function, I use the request.POST to create an instance :
filterbycategory = FilterbyCategory(request.POST)
I then print the form instance, I get this :
<tr><th><label for="id_category">Category:</label></th><td>
<select name="category" id="id_category">
<option value="">---------</option>
<option value="1" selected>BMW</option>
</select></td></tr>
but the option is not selected in the template rendered manually.

I found the solution. I had to get field value directly and to use safe like bellow :
<option value="{{ x.0 }}"{% if FilterbyCategory.category.value|safe == x.0|safe %} selected{% endif %}> {{ x.1 }} </option>
It works like a charm now.

Related

html form select dynamically preselected value (flask)

I have quite simple application written in flask. On the main page I have a form where you select some settings from few dropdown selects. Sth like this:
<form action="/" method="post">
Choose year:
<div class="form-group">
<select class="form-control" id="year" name="year">
<option value='years' selected>years</option>
<option value='quarters' >quarters</option>
{% for year in years %}
<option value={{year}}>{{year}}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<button class="btn btn-default" type="submit">Show statistics</button>
</div>
</form>
One of values is preselected now. However, when I choose a different setting, click submit and render the page again (according to the new settings), I would like to have as preselected not the value that was preselected at the first but the value I have chosen. What is the proper way to do this?
Use an {% if %} statement to decide which option should be selected.
<select class="form-control" id="year" name="year">
<option value='years' {% if choice == 'years' %} selected {% endif %}>years</option>
<option value='quarters' {% if choice == 'quarters' %} selected {% endif %}>quarters</option>
...
</select>
where choice is a variable you pass to the template that holds the value you chose when you submitted the form.

How can I do to display all the name?

Hello I would like to create a select using Django I have a model :
class Test(models.Model):
name = models.CharField(null=True, default=None)
And I would like to create a select with option of name from the table Test.
How can I do this ?
I tried this :
<select class="form-control">
<option value=""></option>
{{ for name in Test }}
<option value="{{ name.id }}">{{ name.name }}</option>
{% endfor %}
</select>
But it does not work...
Could you help me please ?
just change {{ for name in Test }} to {{ for name in Test.all }}
I recommend you to pass the list of Test using the context.
app/view.py
def my_view(request):
context = {
tests: Test.objects.all()
}
return render(request, 'my_html_with_the_select.html', context)
app/templates/my_html_with_the_select.html
<select class="form-control">
<option value=""></option>
{% for test in tests %}
<option value="{{ test.id }}">{{ test.name }}</option>
{% endfor %}
</select>

Efficient way of adding attributes to HTML using Flask with fewer lines of code to select element?

I have a select element which I would like to populate from a database if this information already exists. For example, this is what I did for gender:
<select class="form-control" id="gender">
<option value="-5">Not Selected</option>
{% if current_user.gender == 0 %}
<option value="0" selected>Male</option>
{% else %}
<option value="0">Male</option>
{% endif %}
{% if current_user.gender == 1 %}
<option value="1" selected>Female</option>
{% else %}
<option value="1">Female</option>
{% endif %}
</select>
Now I have another select element with 6 different options (all with integer values 0, 1, 2 ... 5). Is there a way to make it more concise instead of writing 30 lines of code like this with if statement for each one?
Yes, there is for loop in jinja2 templating.
If you have for example a python list which contain all of select options:
options = ['option1', 'option2', 'option3', ...]
<select class="form-control" id="gender">
{% for option in options %}
<option value="{{ loop.index }}"
{% if current_user.gender == loop.index %}
selected
{% endif %}
>{{ option }}</option>
{% endfor %}
<option value="-5">Not Selected</option>
</select>
loop.index represent the current iteration of the loop. (1 indexed)
This is one example, but there is other when you iterating through objects which you've gotten from a database:
objects = [object1, object2, object3, ...]
<select class="form-control" id="gender">
{% for object in objects %}
<option value="{{ object.value }}"
{% if object.value == current_user.gender %}
selected
{% endif %}
>{{ object.name }}</option>
{% endfor %}
<option value="-5">Not Selected</option>
</select>

How do I preserve data in Django templates on a drop-down menu?

I am trying to preserve form data on a registration template on a Django project. I am using ginger statements such as {{ old_data.[data] }}. I have no problem doing it with regular text input (like this):
<div class="form-group">
<input type="text" name="zip_code" id="zip_code" class="form-control input-sm" placeholder="Zip" value="{{ old_data.zip_code }}">
</div>
And with textarea (like so):
<textarea type="area" name="area" id="area" class="form-control
textarea" rows="3" placeholder="Please tell us briefly in what part
of town you live and how far you are willing to travel for
rehearsals and performances. i.e., 'I live in the Heights but I'm
willing to drive anywhere within the loop.'">{{ old_data.area }}
</textarea>
But I cannot figure out how to do it with a drop-down menu. Here is my current code:
<select class="form-control" name="primary_instrument" id="primary_instrument" placeholder="Primary instrument" value="{{ old_data.primary_instrument }}">
<option selected disabled>Primary instrument</option>
{% for instrument in instruments %}
<option value='{{ instrument.id }}'>{{ instrument }}</option
{% endfor %}
</select>
Please help!
You can iterate over it, and check for every element if the value corresponds to the value of that option, if that is the case, you add a selected attribute:
<select class="form-control" name="primary_instrument" id="primary_instrument" placeholder="Primary instrument">
<option selected disabled>Primary instrument</option>
{% for instrument in instruments %}
<option value='{{ instrument.id }}' {% if instrument.id == old_data.primary_instrument %}selected{% endif %}>{{ instrument }}</option>
{% endfor %}
</select>
Note the {% if instrument.id == old_data.primary_instrument %}selected{% endif %}. We thus check if the value is the same, and if so, we add the selected attribute to the <option> tag.

Jinja2 templating boolean variables cleanly

The following code selects all 3 of the options (though only perhaps one is desirable).
<select id="example-getting-started" name="test" multiple="multiple">
<option value="cheese" selected="NO">Cheese</option>
<option value="tomatoes" selected>Tomatoes</option>
<option value="mozarella" selected="maybe">Mozzarella</option>
<option value="mushrooms">Mushrooms</option>
<option value="pepperoni">Pepperoni</option>
<option value="onions">Onions</option>
</select>
It's not hard to convert this to a Jinja2 template correctly, but it's verbose, and its size grows exponentially with the number of boolean tags. Is there a cleaner solution here? In the example below, pizza_dict is a python dict that associates each topping to the boolean value of whether it is on the pizza.
<select id="example-getting-started" name="test" multiple="multiple">
{% for k in pizza_dict %}
{% if pizza_dict[k] %}
<option value="{{ k }}">{{ k }}</option>
{% else %}
<option value="{{ k }}" selected>{{ k }}</option>
{% endif %}
{% endfor %}
</select>
Could you not simplify this to something like:
<select id="example-getting-started" name="test" multiple="multiple">
{% for k in pizza_dict %}
<option value="{{ k }}" {% if pizza_dict[k] %}selected{% endif %}>{{ k }}</option>
{% endfor %}
</select>