Combining radio-button with a dropdown form - html

How can I combine radio-button inside a dropdown select form.
I'll be grateful for your help.
My codes:
index.html
<div class="card-header">
<div class="container">
<div class="row">
<form class="col-md-4">
<select class="form-control select2" >
<option>Select Major Head</option>
{% for major in majors %}
<option>{{ major.pk }}: {{ major.description }}</option>
{% endfor %}
</select>
<button type="button">Display!</button>
</form>
</div>
</div>
</div>

This might not be the best approach, but you can try something like this:
<form class="col-md-4" action="{{ your_url_here }}" method="post">
{% csrf_token %}
<select class="form-control select2" >
<option>Select Major Head</option>
{% for major in majors %}
<option value="{{ major.pk }}">{{ major.pk }}: {{ major.description }}</option>
{% endfor %}
</select>
<input type="submit" value="Select">
</form>
Yes, you need to write a Django form to process the data. You can read more about forms here. The value="{{ major.pk }}" part gives Django views an attribute to recognize, which you are going to use later.
After having filled out the form, you can get the data in your views as such:
def page_objects(request):
if request.method == 'POST':
form = YourForm(request.POST)
if form.is_valid():
answer = form.cleaned_data['value']
Forms are not the easiest thing to do as you need to create your own views and forms, both backend and frontend. You may also try out other form helper libraries like django crispy forms, but that really depends on how much you want to rely on bootstrap and other UI libraries.

Related

How to handle await self.request.post()['users'] with multiple variables from HTML select tag for the same parameter in Aiohttp?

I want to receive users that a user has chosen to create a group chat. In an Aiohttp to get variable from HTML select tag, I use self.request.post()['variablename']:
#login_required
async def post(self):
data = await self.request.post()
chat_topic = data.get('chat_topic', '').lower()
users = data['users']
await Chat.create(topic=chat_topic, users=group_users)
This is my rooms.html:
{% extends 'base.html' %}
{% block content %}
<form class="form-signin" method="POST" action="{{ app.router['create_chat'].url_for() }}">
<h2 class="form-signin-heading">Create new chat</h2>
<label for="chat_topic" class="sr-only">chat topic</label>
<input name="chat_topic" type="text" id="chat_topic" class="form-control" maxlength="32" placeholder="chat topic" required autofocus>
<label for="users"> Choose users: </label>
<select name="users" id="users" multiple="multiple">
{% for user in users %}
<option value="{{ user.id }}">
{{ user.username }}
</option>
{% endfor %}
</select>
<button class="btn btn-lg btn-primary btn-block" type="submit">create chat</button>
</form>
{% endblock %}
Unfortunately, I receive only the last selected user as a string, not all of selected users. How can I get an array of selected users in aiohttp from an HTML select tag?
I know that in Django, I could do something like this:
users = request.POST.getlist('users')
I will appreciate any help!

My form is not saving for some reason... did I made a mistake on my HTML?

I wanted to modify the way my forms is displayed using html and css.
Here is the <form> part of my HTML:
<form action="" method="post" enctype='multipart/form-data'>
{% csrf_token %}
<div>
<input type="text" name="post_title" placeholder="Forum title" id="id_post_title">
<textarea name="post_body" placeholder="Forum content" id="id_post_body"></textarea>
<div class="authors"> <!-- This class is to call my Users model -->
<select name="author" id="id_author">
<option value="">----Select Author----</option>
{% for author in authors %}
<option value="{{ author.first_name }} {{ author.last_name }}">{{ author.first_name }} {{ author.last_name }}</option>
{% endfor %}
</select>
</div>
<div>
<label>
<input type="file" accept="image/" name="forum_image" required id="id_forum_image" >Upload Image
</label>
</div>
<input type="submit" value="Save Post" class="save_post">
</div>
</form>
I tried form.as_p and it all worked just fine. Did I made a mistake in my HTML? Here is my forms.py:
class AddForum(forms.ModelForm):
class Meta:
model = Forum
fields = 'all'
labels = {
'post_title': 'Title of your post:',
'post_body': 'Content of your post:',
'author': 'Author:',
'forum_image': 'Attach image:',
}
def __init__(self, *args, **kwargs):
super(AddForum, self).__init__(*args, **kwargs)
self.fields['forum_image'].required = False
The problem lies with my <option value="{{ something }}". What value needs is {{ something }}'s id and not the name itself.
The code should be:
<option value="{{ author.id }}">{{author.first_name }} {{ author.last_name }}</option>

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

show selected option when render posted form in django

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.