user2225970
user2225970

Reputation:

Django ValidationError in view?! not form

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?

Upvotes: 1

Views: 657

Answers (1)

stett
stett

Reputation: 1411

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).

Upvotes: 1

Related Questions