简体   繁体   中英

ValidationError: “value must be a decimal number”

I have the following Model:

class Listing(models.Model):
    product = models.CharField(max_length=64)
    description = models.CharField(max_length=200)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Listings")
    category = models.CharField(max_length=64, blank=True)
    created = models.DateField()
    starting_price = models.DecimalField(max_digits=6, decimal_places=2, default=decimal.Decimal(0))
    current_price = models.DecimalField(max_digits=6, decimal_places=2, default=starting_price)

In my views.py I use an instance of a Django Form class to ask the user for the input. I get the following error ['“auctions.Listing.starting_price” value must be a decimal number.'] However, when I check the Local Vars on the error page I can see the the value of starting_price = Decimal('10.00')

So clearly the value of auctions.Listing.starting_price is a decimal. There are no other entries which could cause this problem.

The Form I use looks like that:

class NewListingForm(forms.Form):
    product = forms.CharField(max_length=64)
    description = forms.CharField(widget=forms.Textarea)
    category = forms.CharField(max_length=64, required=False)
    starting_price = forms.DecimalField(max_digits=6, decimal_places=2)

When Posting I evalute the data like so:

if entry_form.is_valid():
    product = entry_form.cleaned_data["product"]
    description = entry_form.cleaned_data["description"]
    category = entry_form.cleaned_data["category"]
    starting_price = entry_form.cleaned_data["starting_price"]

And I save the model entry via:

listing = Listing(product=product, description=description, user=user, category=category, created=created, starting_price=starting_price)
listing.save()

I'd really appreciate any ideas on that.

The problem is the default=starting_price part:

class Listing(models.Model):
    # …
    current_price = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        default=starting_price
    )

When the class itself is interpreted, starting_price is a Decimal , so it will try to assign a Decimal as value to another DecimalField , not a Decimal . ,因此它将尝试将Decimal 作为分配给另一个DecimalField而不是DecimalSince a DecimalField accepts certain types of objects like strings, Decimal s, etc. but not a DecimalField , that will raise an error.

You can simply pass the value to both the starting_price and current_price , for example:

Listing.objects.create(
    product=product,
    description=description,
    user=user,
    category=category,
    created=created,
    starting_price=starting_price,
    
)

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