1

i have problem with validating Django Form because i can't save model before cleaning of course. I have reservation model:

class Reservation(models.Model):
    from = models.DateTimeField()
    to = models.DateTimeField()
    total_price = models.DecimalField()
    paid = models.DecimalField()

    def calculate_price(self):
        self.total_price = some_magic(self.from, self.to)

and form:

class ReservationForm(forms.ModelForm):
    payment_amount = forms.DecimalField()

    class Meta:
        model = Reservation

    def clean(self):
        ????

I want to verify in clean method if payment_amount is not greater than total_price but total_price is not updated - i call calculate_price() after saving model.

Can i raise ValidationError in view after price calculation?

1
  • @RahulGupta Just for simplicity, i overwrote .save(self) method of reservation. Commented Sep 25, 2015 at 8:52

1 Answer 1

1

You might consider putting the contents of calculate_price into a method which doesn't modify the Reservation model instance's data.

For example, at the moment you have the pretend function some_magic. In clean you could put something like this:

def clean(self):
    data = super(ReservationForm, self).clean()
    total_price = some_magic(data.get('from'), data.get('to'))
    if data.get('payment_amount') > total_price:
        raise ValidationError("Payment amount should not exceed total price of $%s" % total_price)
    return data

The idea is to untie the calculation of your price-calculation from the act of saving it on the model, so that it can be used in multiple places (ie. model save method or form validation).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.