Ive got a DecimalField in one of my forms where a user enters a price.
Say the user enters 11.00, now when i retrieve it as in (priceform.cleaned_data) it returns
Decimal('11.00')
so it looks like
price = Decimal('11.00')
which triggers a validation error when i try to insert it into the database.
I'm coming up blank to any solutions for this
models.py
class Bid(models.Model):
title = models.CharField(max_length=64, blank=True)
date_time = models.DateTimeField(default=timezone.now, blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
user = models.CharField(max_length=64)
forms.py:
class BidForm(ModelForm):
class Meta:
model = Bid
fields = ['price']
views.py:
if request.method == "POST":
bidform = BidForm(request.POST)
if bidform.is_valid():
price = bidform.cleaned_data['price']
bid = Bid.objects.create(title=title, price=bidform, user=username)
bid.save()
CodePudding user response:
The price
should be the price
, not bidform
:
if request.method == 'POST':
bidform = BidForm(request.POST, request.FILES)
if bidform.is_valid():
bid = Bid.objects.create(
title=title,
price=bidform.cleaned_data['price'],
user=username
)
You can however let the form do the work:
if request.method == 'POST':
bid = Bid(
title=title,
user=username
)
bidform = BidForm(request.POST, request.FILES, instance=bid)
if bidform.is_valid():
bid = bidform.save()