TheNone
TheNone

Reputation: 5802

'+' in django form

I have a select box that may have option with values in -20 and +20 range:

class MyForm(forms.ModelForm):
    class Meta:
        i0=xrange(-20, 20, 0.25)
        c = tuple(("%g" % x , "%g" % x) for x in i0)
        model = MyModel
        widgets = {
            'my_field' : forms.Select(choices=c),

        }

Output is:

<select>
    <option value="-20">-20</option>
    <option value="-19.75">-19.75</option>
    <option value="-19.5">-19.5</option>
    <option value="-19.25">-19.25</option>
    <option value="-19">-19</option>
    .
    .
    .
    <option value="19">19</option>
</select>

But I want a '+' symbol in positive digits. i0=xrange(-20, +20, 0.25) not solving the issue. How can I add '+' symbol in positive digits in options?

Thanks in advance

Upvotes: 1

Views: 38

Answers (2)

James Khoury
James Khoury

Reputation: 22329

Without access to a machine with python I cant test but you should be able to do:

  c = tuple(("%g" % x , "%+g" % x) for x in i0)

http://docs.python.org/release/3.0/library/stdtypes.html#old-string-formatting-operations

Should also work in earlier python versions

EDIT:- to remove the + from a Zero value:

 c = tuple(("%g" % x , "%+g" % x) for x in i0 if x != 0 else ("0", "0"))

Upvotes: 2

zinking
zinking

Reputation: 5695

define this field as characters, but do validation in Integer. this should be the fast solution

Upvotes: 0

Related Questions