0

I have the following in my forms.py to define choices on a form input:

selection = forms.TypedChoiceField (label="Format", choices = (("Choice1", "Choice1"), ("Choice2", "Choice2"), ("Choice3", "Choice3"),widget = forms.RadioSelect, required= True)

And in my template, I currently have the following line of code which allows people to select one of these choices.

{{ formtoaddselection.selection }}

This is fine in general, but I have a corner case where I want to sometimes overwrite those default choices to say CornerCase1 and CornerCase2.

Is it possible to override those defaults in the template, and if so, how?

user1328021
  • 9,110
  • 14
  • 47
  • 78
  • you could use some javascript? – nathan hayfield Jan 22 '13 at 16:40
  • Why override the values in your template? Use dynamic choices and put the logic in your form class where it belongs: http://stackoverflow.com/q/3419997/630877 – arie Jan 22 '13 at 17:06
  • Thanks @arie;.. the problem with that method (I think) is that I don't have the variable I need by the time the view/form is loaded... It's after a user clicks on a particular item that I know the choices I need to populate... – user1328021 Jan 22 '13 at 18:03

1 Answers1

2

The only way to have non trivial behavior in the template layer is to build template tags.

Something like:

@register.simple_tag
def override_form_choices(field, *args, **kwargs):
    field.choices = [(x, x) for x in args]
    return field


{% override_form_choices formtoaddselection.selection 'foo' 'bar' 'baz' %}

You may find an assignment tag is more appropriate here / readable / flexible here.

Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245