0

When I try to test my form with an email which has already been entered into the database it doesn't give the error message like it should, it redirects back to the homepage.

My views.py file looks like this:

from django.shortcuts import render
from .forms import LotteryForm
from django.http import HttpResponseRedirect

# Create your views here.
def lottery_list(request):
    return render(request, 'lottery/lottery.html', {})

def lottery_new(request):
   if request.method == 'POST':
       form = LotteryForm(request.POST)
       if form.is_valid():
           form.save()
            return HttpResponseRedirect('lottery_submitted')
       else:
            return render(request, 'lottery/lottery.html' {'form': LotteryForm()})
   else:  
       form = LotteryForm()
       return render(request, 'lottery/lottery.html', {'form': LotteryForm()})

My form is:

from django import forms
from django.db import models
from django.forms import ModelForm
from .models import Lottery
from .models import Lottery_user
from django.core.exceptions import ValidationError

class LotteryForm(forms.ModelForm):
    lottery_type = forms.ModelChoiceField(queryset = Lottery.objects.all(), empty_label=None)
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)
    lottery_numbers = forms.CharField(max_length=12, required=True)
    email = forms.EmailField(required=True)
    telephone = forms.CharField(max_length=18,
                  error_messages={'invalid':'Enter a valid mobile number',
                                  'required':'Enter a valid mobile number'})

    def clean_email(self):
        email = self.cleaned_data['email']
        if Lottery_user.objects.filter(email=email).exists():
             raise ValidationError("Email already exists")
             return email
        if Lottery_user.objects.filter(email=self.cleaned_data['email']).exists():
            raise ValidationError("You've already entered")
            return email

    class Meta:
         model = Lottery_user
         fields = ['lottery_numbers', 'lottery_type', 'first_name', 'last_name', 'email', 'telephone',]

Template form:

 <form action="{% url 'lottery_new'  %}" method="post">
        {% csrf_token %}
        <div class="fieldWrapper">
            <label for="lotterytype">Choose a lottery:</label>
            {{ form.lottery_type }}
            <p>See <a href=lottery_instructions>instructions and rules</a></p>
        </div>
        <div class="fieldWrapper">
            <label for="lotterynumbers">Lottery Numbers:</label>
            {{ form.lottery_numbers }}
        </div>
        <div class="fieldWrapper">
            <label for="firstname">First name:</label>
            {{ form.first_name }}
        </div>
        <div class="fieldWrapper">
            <label for="lastname">Last name:</label>
            {{ form.last_name }}
        </div>
        <div class="fieldWrapper">
            {{ form.email.errors }}
            {{ form.email.non_field_errors }}
            <label for="email">Email:</label>
            {{ form.email }}
        </div>
        <div class="fieldWrapper">
            <label for="phonenumber">Telephone Number:</label>
            {{ form.telephone }}
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
    </form>

I want a user to not be able to enter twice with the same email, so it should error when the user clicks submit with a used email address.

Also, does anyone know how to get the error messages to show before the user submits rather than afterwards?

2
  • Could you append the code for rendering the form in templates. Commented Dec 31, 2015 at 12:26
  • I've just added it for you Commented Dec 31, 2015 at 12:29

1 Answer 1

2

You return a newly instantiated form when the form is invalid, when you should instead return the invalid form (with the errors). Try:

def lottery_new(request):
   if request.method == 'POST':
       form = LotteryForm(request.POST)
       if form.is_valid():
           ....
       else:
           return render(request, 'lottery/lottery.html' {'form': form})
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that worked. Although, it still allows me to submit the form whilst giving an error message.
Do you know why I can't get the error messages to show before the user submits?
@CNB : very obviously because the validation happens on the server, so until the user actually submits the form there's nothing to validate xD
@CNB: What bruno says is correct. Generally you can use javascript (and to some degree HTML5) for client side validation, but in your case you have to check the database for the email's existence, so you have to submit the email (ie the form) first for that check to happen.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.