Display selection field in Django template - python-3.x

I 'm trying to find a workable solution for my problem. I have found two similar questions answered before, but still I can't solve it. If we have a class like this:
from django.db import models
class Consumer(models.Model):
SIZES = (
('S', 'Small'),
('M', 'Medium'),
('L', 'Large'),
)
name = models.CharField(max_length=60)
size = models.CharField(max_length=2, choices=SIZES)
And I did in my view and template like this (Learned from one tutorial)
***view with combined queries***
def staff_filter(request):
qs = Consumer.objects.all()
size= request.GET.get('size')
# I have some other queries in between ....
if is_valid_queryparam(size) and size!='Choose...':
qs = qs.filter(size=consumer.get_size.display())
return qs
def filter(request):
qs=staff_filter(request)
context={
'queryset':qs,
'consumer':consumer.objects.all()
}
return render(request, 'filter.html',context)
**template***
<div class="form-group col-md-4">
<label for="size">size</label>
<select id="size" class="form-control" name="size">
<option selected>Choose...</option>
{% for size in consumer.get_size.display %}
<option value="{{ size }}">{{size}}</option>
{% endfor %}
</select>
</div>
How should I correct it? Thanks!
Display selection field in Django template

You mispelled consumer in context in view
'consumer':consumer.objects.all() #You mispelled consumer here
Try this:
'consumer':Consumer.objects.all() # Consumer, first letter should be capital
I think you misplelled in above code so that's why you are not getting values on template

You do not need any get_size.display() method in a template. If consumer variable is an object of the Consumer class then you just have to do like this:
<select>
{% for val, text in consumer.SIZES %}
<!--
Here SIZES is a tuple variable of your Consumer class,
while consumer is an instance of the Consumer class then you can just
call SIZES tuple from any of its instances.
-->
<option value="{{ val }}">{{ text }}</option>
{% endfor %}
</select>
If consumer is a variable from the context you are passing in your
view, then it's a queryset. So in this case you should loop over your queryset first, then call SIZES variable from every object inside the loop:
{% for object in consumer %}
<select>
{% for val, text in object.SIZES %}
<option value="{{ val }}">{{ text }}</option>
{% endfor %}
</select>
{% endfor %}

Related

in twig file after split the value

in twig file after spliting the value i'm getting output like this in a browser
<select class="form-control" id="eventCustomerID" name="eventCustomer">
<option value="64" name="64">64</option>
<option value="demou22_6hhh" name="demou22_6hhh">demou22_6hhh</option>
</select>
but i need an output to be like this
<select class="form-control" id="eventCustomerID" name="eventCustomer">
<option value="64" name="64">demou22_6hhh</option>
</select>
this is my code in a twig file
<select class="form-control" id="eventCustomerID" name="eventCustomer">
{% set tags = 64|demou22_6hhh|split('|',1) %}
{% for x in tags %}
<option value="{{ x }}" name="{{ x }}">{{ x }}</option>
{% endfor %}
</select>
I am stuck with this can someone help me out with this issue.
To achieve your required output, you shouldn't use a for loop, but access the elements directly.
<select class="form-control" id="eventCustomerID" name="eventCustomer">
{% set tags = "64|demou22_6hhh"|split('|') %}
<option value="{{ tags[0] }}">{{ tags[1] }}</option>
</select>
demo
Note about the second argument you are passing to the filter split
Not sure why you are passing 1 as the second argument. By setting this parameter to 1, you are limiting the output to one element in the array. More information here.

A Simple Calculator using Django

I want to create a website where the user is asked to type a given number to get the square number and the square root.
This is from index.html:
<div class="d-flex typeW">
<form action="add">
Enter a number : <input type="text" name="num1">
<input type="submit">
</form>
</div>
This is from the result page (where you can see the result):
<div class="d-flex title2">
<h2>
{% block content %}
{{result}}
{% endblock %}
<br><br>
This is from view:
def add(request):
num1 = int(request.GET["num1"])
return render(request, 'result.html' , {result2: num1 * num1})
Now I want to take the square root of that number but I'm not sure how.
How do I take one input and then do two calculations by using two functions?
help much appreciated
Simply do two calculations in your view and return both results within the context. You can then access all values in the context and render them in the template.
import math
def add(request):
# Get the user input
num1 = int(request.GET["num1"])
# Calculate square
num1_square = num1 ** 2
# Calculate root
num1_root = math.sqrt(num1)
# return context
context = {
'square': num1_square,
'root': num1_root
}
return render(request, 'result.html' , context)
# template
<div class="d-flex title2">
<h2>
{% block content %}
{{ square }}
{{ root }}
{% endblock %}
<br><br>

Is there any way to iterate over list inside list in django template?

I have a list a = [[1000,3000], [4000-5000]], i would like to show it has
1000-3000
4000-5000 in template. But i'm getting only the first object.
What i tried is,
products.html
{% for i in price_group %}
<label>
<input class="uk-radio" type="radio" onchange="$('#form').submit();" name="price" value="{{ i.0.0 }};{{ i.0.1 }};price;first" checked>
{{ i.0.0 }} - {{ i.0.1 }}
</label>
{{ price_group.pop.i }}
{% endfor %}
I used pop functionality to remove current from the list and take the next one, but it's not working as expected.
it is showing only the first element in the list. Please correct me if I am wrong. What I want is it has a price range like.
1000-3000
4000-5000..like wise. Please help me.
You are accessing only first element of the list, you need to update your code to access all the elements like this:
{% for i,j in price_group %}
<label> <input class="uk-radio" type="radio" onchange="$('#form').submit();" name="price" value="{{ i }};{{ j }};price;first" checked>
{{ i }} - {{ j }}
</label>
{% endfor %}

<option {% if 'condition.' == 'condition....'%}selected{%endif%}> </option> not working in Django custom select

I am passing two objects 'editsub_obj' and 'cat' both key-value pairs to the template.
The main aim is to keep option tag selected when name from both object list matches but the code is not working.
<select class="form-control" id="" name="cat_name" required>
{% if not editsub_obj %}
{% for data in cat %}
<option value="{{data.id}}">{{data.category_name}}</option>
{% endfor %}
{% else %}
{% for data in cat %}
{% if editsub_obj.category_name == data.category_name %}
<option value="{{data.id}}" selected>{{data.category_name}}</option>
{% else %}
<option value="{{data.id}}">{{data.category_name}}</option>
{% endif %}
{% endfor %}
{% endif %}
</select>
Expected :
selected should be selected with the category_name matches in both objects list.
Actual :
none of the options are showing as selected.
Your code can reduce to ::
<select class="form-control" id="" name="cat_name" required>
{% for data in cat %}
<option value="{{data.id}}"
{% if editsub_obj and editsub_obj.category_name in data.category_name %}
selected
{%endif%}>
{{data.category_name}}
</option>
{% endfor %}
</select>

setting a Twig variable

Is it possible to set a option value to a twig variable?
I want to accomplish something like this.
<select>
<option value="10">10</option>
</select>
{% set optVal = option value here %}//don't know if this is possible.
{% if optVal %}
//do something here
{% endif %}

Resources