简体   繁体   中英

Django percentage form field

I want to use a percentage form field in Django. Basically in my models I have a float field. The default when using a model form is a text input that validates that it is a number. If the user wants to enter 40%, they must enter 0.4. What I want is an optional percentage symbol that they can enter. Therefore, they can either enter 0.4 or 40%.

Is there something like that built into Django? If not, why? I would expect this to be something that is used often. Or do I tell them it is an percentage field and force them to just fill in 40?

you can create your own validator easy enough

def valid_pct(value):
    if value.endswith("%"):
       return float(value[:-1])/100
    else:
       try:
          return float(value)
       except ValueError:          
          raise ValidationError(
              _('%(value)s is not a valid pct'),
                params={'value': value},
           )

... models.py

class MyModel(models.Model):
    pct = models.StringField(validators=[valid_pct])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM