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 >
<label for="size">size</label>
<select id="size" 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
CodePudding user response:
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
CodePudding user response:
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>