Reputation: 455
I have created my form like so,
class PartialOrderItemform(forms.Form):
option = forms.ModelChoiceField(queryset = OptionalItems.objects.all(),widget= forms.RadioSelect())
def __init__(self,item ,*args, **kwargs):
super(PartialOrderItemform, self).__init__(*args, **kwargs)
self.fields['option'].queryset = OptionalItem.objects.filter(item=item)
views.py
def show_item(request,id):
....
final_form = form.PartialOrderItemform(item=id)
....
All the above is working just fine, my problem is rendering in the templates, doing some thing like this {% for option in form.option %} {{option}}
works fine, why is this not working {{ option.price }}
.
Clearly there is something i am not understanding thus my asking here, why can't i access the option's attributes and what is the right way to go about it.
Upvotes: 2
Views: 2560
Reputation: 15594
Unfortunately ModelChoiceField's iterator only returns tuple (value, label), so you need to make some overriding to make it work, this link should help you out:
Upvotes: 0
Reputation: 2405
Have you tried using a model_formset? Not sure why you're using a regular form and initialising the queryset twice, when you want to make a formset based on a filtered Model queryset. Something like this:
class PartialOrderItemformSet(BaseModelFormSet):
def __init__(self, item, *args, **kwargs):
super(PartialOrderItemformSet, self).__init__(*args, **kwargs)
self.queryset = OptionalItem.objects.filter(item=item)
Now in your template you should be able to access the underlying Models unary methods inside your for loop with:
{{form.instance.price}}
Upvotes: 0
Reputation: 600041
You're not really supposed to iterate over form fields like that. Just do:
{{ form.option }}
Upvotes: 0