fcp
fcp

Reputation: 89

Django Forms: Cannot show Validation Error

I have a Django Form where I allow the user to submit a value only if his password matches a predefined password set by me : Pass_matcher

Validation works fine, such that if passwords match, value is entered and stored and if not, nothing happens.

However I want that if passwords do not match, I show a simple custom warning message. I looked at other SO questions such as here and here, but I can't seem to get it right.

Note: If the user enters the correct password I do not want to redirect to another page.

forms.py

from django import forms

class TactForm(forms.Form):

        password = forms.CharField(widget=forms.PasswordInput(
                attrs = {
                        'class' : 'form-control mb-2 mr-sm-2 mb-sm-0',
                        'placeholder' : 'Enter Password:',
                        'id' : 'inlineFormInput',
                        'required' : 'true'
                }
        ), required = True, label='Tact Password', max_length=100)


        tacttime = forms.CharField(widget=forms.TextInput(
                attrs = {
                        'class': 'form-control mb-2 mr-sm-2 mb-sm-0',
                        'placeholder': 'Enter Tact Time:',
                        'id' : 'inlineFormInput2'
                }
        ),label='Tact Time', max_length=100)

        def clean(self):
                cleaned_data = super(TactForm,self).clean()
                password = cleaned_data.get('password')
                current_tact = cleaned_data.get('tacttime')

                if password != 'Pass_matcher':
                        print('incorrect') #this prints to console if incorrect
                        raise forms.ValidationError('Incorrect Password') # this does not work

                else:
                        print('correct') #this prints to console if correct
                        return cleaned_data

views.py

def details(request):

    form = TactForm(request.POST or None)
    if request.method == 'POST':
            form = TactForm(request.POST)
            if form.is_valid():
                    print('here1')
                    current_tact = form.cleaned_data['tacttime']
                    password = form.cleaned_data['password']

            else:
                    form = TactForm()

   return render(request, 'linedetails/index.html',{'form':form})

template

<div class="user_in" style="text-align:center;">
                <form class="form-inline" method="POST" action="{% u$
                        {% csrf_token  %}
                        {{ form.password }}
                        {{ form.tacttime }}
                        <br>
                        <button type="submit" class="btn btn-outline>
                </form>
</div>

The below code is experimental

{% if form.errors %}
    {% for field in form %}
        {% for error in field.errors %}
            <div class="alert alert-danger">
                <strong>{{ error|escape }}</strong>
            </div>
        {% endfor %}
    {% endfor %}
    {% for error in form.non_field_errors %}
        <div class="alert alert-danger">
            <strong>{{ error|escape }}</strong>
        </div>
    {% endfor %}
{% endif %}

I cannot understand why the raise forms.ValidationError('Incorrect Password') is not shown if the statement above it is correctly printed to terminal.

I am thinking that I have something missing in else statement of the views.py script.

Thanks for any suggestions.

Upvotes: 0

Views: 1699

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

You redefined form instance if form is not valid. just remove else block to fix it:

def details(request):

    form = TactForm(request.POST or None)
    if request.method == 'POST':
            form = TactForm(request.POST)
            if form.is_valid():
                    print('here1')
                    current_tact = form.cleaned_data['tacttime']
                    password = form.cleaned_data['password']

   return render(request, 'linedetails/index.html',{'form':form})

Also you actually dont need if request.method == 'POST' validation since form will be populated with post data automatically here form = TactForm(request.POST or None). So you can simply rewrite your view to this:

def details(request):
    form = TactForm(request.POST or None)
    if form.is_valid():
        print('here1')
        current_tact = form.cleaned_data['tacttime']
        password = form.cleaned_data['password']

    return render(request, 'linedetails/index.html',{'form':form})

Upvotes: 1

Related Questions