Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6707799
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T07:40:56+00:00 2026-05-26T07:40:56+00:00

I have a DecimalField in a model. In the ModelForm associated with the model,

  • 0

I have a DecimalField in a model. In the ModelForm associated with the model, I am trying to customize the field to allow simple math (just division) before processing.

For example, I want to allow 1/2 to be typed into the form and then have 0.50000 saved to the database.

In my forms:

def clean_qty(self):
    data = self.cleaned_data['qty']
    if type(data) == int or type(data) ==float: #need to catch decimal too?
        return data
    elif re.match("^(\d+)/(\d+)$", str(data)):
        # do math on, return value
    else:
        raise forms.ValidationError("Enter number or fraction")

When I submit the form with 1/4 I get ‘Enter a number.’ And using 1 raises ‘Enter number or fraction’ as my validation error, neither of which are options from my clean method.

I think it’s being raised by the to_python method for the DecimalField? Can I customize the to_python field without having to define a custom form field type or model field type?
Or what else can I do to allow this behavoir?


Update for solution:

I ended up changing the DecimalField to a FloatField. My inexperience with the Decimal class made it surprisingly hard, and there was no reason I needed a decimal over a float. Also, as suggested, I used a CharField in the Form.

here’s the validation:

class SomeForm(ModelForm):  
    qty = forms.CharField(max_length=30)

def clean_qty(self):
    data = self.cleaned_data['qty']
    try:
        float_data = float(data)
        return float_data
        ## this is for integers or floats with no attempted division
    except:
        try:
            match =re.match("(?P<num>([0-9.]+))/(?P<den>([0-9.]+))", str(data))
            num = float(match.groupdict()['num'])
            den = float(match.groupdict()['den'])
            result = num/den
            return result
        except:
            raise forms.ValidationError("Enter a number or fraction")

I’m really using/abusing the try-except syntax to allow for sloppier regex. For example ‘.’ and ‘1.2.3’ are allowed by the regex for the numerator and denominator, but they get caught when calling float(). So it’s quite hackish (in my mind) but I thought I’d post it for others.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T07:40:56+00:00Added an answer on May 26, 2026 at 7:40 am

    Create a custom form with a text field and do the conversion to decimal when the form is submitted.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a field in my model that's of type DecimalField . Even though
I have a model form that contains a DecimalField() with max_digits set to 5.
I have a model which looks like this: class MyModel(models.Model) value = models.DecimalField() date
I have a model with a decimal field. The output of: def special_method(self): return
I have a model like this. #models.py class Payment(models.Model): unit_price = models.DecimalField(max_digits=12, decimal_places=2) discount
I have this models: class Balanta(models.Model): data = models.DateField() class Conturi(models.Model): cont=models.PositiveIntegerField() cont_debit=models.DecimalField(default=0, max_digits=30,
I have a simple hierarchic model whit a Person and RunningScore as child. this
I have a sample form: class AdminDiscountForm(ModelForm): class Meta: model = Discount exclude =
Let's say I have a CarModel(models.Model) that uses price = models.DecimalField() : import CarModel
I have a model: class ItemPrice(models.Model): price = models.DecimalField(max_digits=8, decimal_places=2) # ... I tried

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.