The Real Codeslinger
The Real Codeslinger

Reputation: 312

How to make ValidationError activate in this example

I have problem with ValidationError.

forms.py

from django import forms

class life_contract_data(forms.Form):
    age = forms.CharField()
    period = forms.CharField()
    premium = forms.CharField()
    percentage = forms.CharField()

views.py

from django.shortcuts import render
from .forms import *
from django import forms

def contract_output(request):
    form = life_contract_data(request.POST)

    age = range(int(request.POST['age']),int(request.POST['age'])+int(request.POST['period']))
    period = range(1,int(request.POST['period'])+1)
    premium_period = range(1, int(request.POST['period']))
    premium = (request.POST['premium'])
    percentage = int(request.POST['percentage'])
    premium1 = []
    premium_total_year = []
    premium1.append(int(premium))
    premium_total_year.append(int(premium1[0])*12)

    for pre in premium_period:
        premium1.append((premium1[pre-1]*percentage)/100 + premium1[pre-1])
        premium_total_year.append(int(premium1[pre])*12 + int(premium_total_year[pre-1]))

    if int(request.POST['age']) >= 65:
        death_capital = 50000000
    else:
        death_capital = 100000000

    if int(request.POST['age']) >= 65 and int(request.POST['period']) > 5:
        raise forms.ValidationError("Age must be lower than 65") #THE CRAZY PROBLEM

    return render(request, 'life/contract_output.html', { 
        'form':form, 
        'age':age,
        'period':period, 
        'premium':premium1, 
        'percentage':percentage,
        'death_capital':death_capital,
        'premium_total_year':premium_total_year,
    })

Added template.html

template.html

<form action="/life/life_contract/contract_output/" method="post">{% csrf_token %}
    {% for field in form %}
        <div class="float" id="form_fields">{{field}}{{field.label}}</div><br />
    {% endfor %}
    <input type="submit" value="Submit" />
</form>

Actually I want if user inputs age>=65 and period>5, he/she faces an error to correct his/her input. But I see this error message from django:

[u'Age must be lower than 65']

Where is the problem???

Upvotes: 1

Views: 3612

Answers (1)

Sayse
Sayse

Reputation: 43330

The problem you're having is that you're doing the validation in the view rather than letting the form handle it inside the form's clean method

class life_contract_data(forms.Form):
    age = forms.CharField()
    period = forms.IntegerField()
    premium = forms.CharField()
    percentage = forms.CharField()

    def clean(self):

        cleaned_data = super(life_contract_data, self).clean()

        if cleaned_data.get('age') >= 65 and cleaned_data.get('period') > 5:
            raise forms.ValidationError("Age must be lower than 65")

        return cleaned_data

Your view will also need to be changed to called is_valid instead

def contract_output(request):
    form = life_contract_data(request.POST)

    if not form.is_valid():
        return render(request, 'life/contract_output.html', { 'form':form })

    # Do something if it is valid       

<form action="/life/life_contract/contract_output/" method="post">
    {% csrf_token %}
    {{ form }}
</form>

For more information, see Cleaning and validating fields that depend on each other

Upvotes: 3

Related Questions