Django 3 Pass Get The Selected Value Dropdown select option - python

Django dropdown option selected. Get data in template and select option. My code is.
views.py
def home(request):
compType = Type.objects.all()
comptype = request.GET.get('comp_type')
context = {
'compType': compType
}
return render(request, 'compapp/dashboard.html', context)
search.html
<div class="form-group">
<label>Type</label>
<select class="form-control select2" name="comp_type" style="width: 100%;">
<!-- <option disabled="true" selected >Company Type</option> -->
{% for i in compType %}
<option value="{{ i }}" {% if request.GET.items == i %}selected{% endif %}>{{ i }}</option>
{% endfor %}
</select>

imagine you have a form, (search form), that user filled it and submitted. you received this form and made the queryset and then you want to show a page contains the search results and, also the form has its fields filled with selected values. So you have to pass that values to the results page too! 'request.GET.items' is not working ever.
what you should do is:
if the had a field named 'dr_select', in the views.py search function you should get that fields value via
selected = get_object_or_404(Type, id==int(request.GET['dr_select']))
then pass 'selected' to the results page, and then in that template you can do what you want.
{% for item in compType %}
<option value="{{ item.id }}"
{% if selected == item %}selected{% endif %}>{{ item } </option>
{% endfor %}
*note: because I used 'item.id' for 'value' in 'option' tag, so in backend I have to filter the Model by id too.

Related

User input in HTML form not captured in Python correctly

i have this html form where user can choose name from a list :
{% block main %}
<form action="/ballot" method="post">
1st Choice
<select name="name1">
<option disabled selected value="">name</option>
{% for candidate in candidates %}
<option value={{ candidate }}>{{ candidate["name"] }}</option>
{% endfor %}
</select><div></div>
In python, i request for this data "name1" using this code
name1= request.form['name1']
return "Username is " + name1
And the result is below :
Username is {'id':
Note that "{'id':" is nowhere in my code
How do i get the correct value from html form
On your for loop value must be between ":
Try editing from this
<option value={{ candidate }}>{{ candidate["name"] }}</option>
To this:
<option value="{{ candidate }}">{{ candidate["name"] }}</option>

How to get the selected value from html select with django

I would like to know if it's possible to get the selected value from a select HTML without using a submit input? Because when I hit the submit, the value selected is returned but it reloads the web page and the select goes back to it's intial state.
Here is my code to visualize better:
views.py
def index(request):
id_desi = request.POST.get('drop_desi')
return render(request, 'index.html', {'designation_liste': df.designation_liste})
index.html
<form action="{% url 'DataMat-index' %}" method="POST">{% csrf_token %}
<select name="drop_desi">
<option disabled selected value> -- select value -- </option>
{% for i in designation_liste %}
<option value="{{ i }}">{{ i }}</option>
{% endfor %}
</select>
<input type="submit" value="valider">
</form>

get values from html select in views with django

I would like to get the value and even the string if possible of the selected value in my HTML file.
index.html
<form action="#" method="post">
<select id="drop1">
<option disabled selected value> -- select value -- </option>
{% for i in df %}
<option value="{{ i }}">{{ i }}</option>
{% endfor %}
</select>
</form>
views.py
def index(request):
if request.method == 'POST':
selected_value = request.POST.get('drop1')
print(selected_value)
else:
return render(request, 'index.html', {'df': df.designation_list})
With this, nothing is returned. I saw that I have to use <form></form> to get an html value but I can't find what to put in the action= field.
Can you see what is missing in my code?
Thanks in advance
The action attribute specifies where to send the form-data when a form is submitted.
In your case, you have to add the url of the view that will hand that data. For example:
<form action="{% url 'index' %}" method="post">
<select id="drop1">
<option disabled selected value> -- select value -- </option>
{% for i in df %}
<option value="{{ i }}">{{ i }}</option>
{% endfor %}
</select>
</form>
Note: Change the index with the name you specified in your URL pattern.

Problem with 'Cannot assign' error in django

I have something like this in my template.
<form action="" method="POST">
{% csrf_token %}
<select name='section'>
{% for item in all_sections %}
<option>{{ item.SectionName }}</option>
{% endfor %}
</select>
</form>
and in my view.py page:
obj=models.Section.objects.all()
context={
'all_sections':obj,
}
return render(request,'matab/add-service.html',context)
but i get this is error while saving data:
Cannot assign "'{item}'": "Services.Section" must be a "Section" instance.
also my models.py is like this:
class Section(models.Model):
SectionName=models.CharField(max_length=50)
SectionId=models.CharField(max_length=10)
class Services(models.Model):
Section=models.OneToOneField(
Section,
on_delete=models.CASCADE,
)
how can i solve it?
Services.Section is a OneToOneField, so you need to assign Section instance, not its name.
Depending on your code, it might work if you set the option value to the pk.
<select name='section'>
{% for item in all_sections %}
<option value="{{ item.pk }}">{{ item.SectionName }}</option>
{% endfor %}
</select>
As Iain suggests in the comments, it would be better to change your views to use Django forms instead of manually render select inputs.

Can't get form data in view function: Django

I need to submit a string to a view function via a dropdown menu and submit button.
in my template I have:
<form action="{% url 'exec_task' %}" method="post">
{% csrf_token %}
<select id="select_task" form="select_task" name="select_task">
{% for task in available_tasks %}
<option id="selected_task" value="{{ task }}">{{ task }}</option>
{% endfor %}
</select>
<input class="button" type="submit" value="Run Selected Task">
</form>
in my view function I have:
def exec_task(request):
if request.method == 'POST':
task = request.POST.get('select_task')
print(task)
getattr(tasks, task)(0)
return redirect('management')
The print(task) always comes out as None, which generates an error when I try to call it via getattr in the next line.
I've read through all the questions and tutorials I can find on this and I don't know what I'm doing wrong, but when I print the request.POST object, all I get is the csrf token. The QueryDict has nothing else in it.
Any ideas?
As discussed in comments please remove
form="select_task" from select tag.
So final select tag / html would be.
<form action="{% url 'exec_task' %}" method="post">
{% csrf_token %}
<select id="select_task" name="select_task">
{% for task in available_tasks %}
<option id="selected_task" value="{{ task }}">{{ task }}</option>
{% endfor %}
</select>
<input class="button" type="submit" value="Run Selected Task">
</form>

Categories

Resources