Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Forms custom error message in views

This is my view:

if request.method == 'POST':
        form = TeacherRegister(request.POST)
        #Gets school object from email domain.
        email = form['email'].value().split('@')[1]
        try:
            school = School.objects.get(email_domain = email)
        except ObjectDoesNotExist:
            #add custom error message here

        if form.is_valid():
            user, Teacher = form.save()
            Teacher.school = school
            Teacher.save()
            user.groups.add(Group.objects.get(name='Teacher'))
            #user.is_active to stop users logging in without confirming their emails

            user.is_active = False
            user.save()
            #Sends confirmation link.
            send_confirmation_email(request, user)

            args = {'email': user.email,
                    'link': user.Teacher.school.email_website}

            return render(request, 'email/token_sent.html', args)

        else:
            args = {'form': form,}
            return render(request, 'users/teachers.html', args)

These lines are what I am trying to work with:

email = form['email'].value().split('@')[1]
try:
    school = School.objects.get(email_domain = email)
except ObjectDoesNotExist:
    #add custom error message here

This is the HTML I have for the email field:

<div class="required field" >
            {{ form.email.label }}
            {{ form.email }}
            {{ form.email.help_text }}
           <!-- <label>Email</label>
           <input placeholder="Email" type="email" name="email" autofocus="" required="" id="id_email"> -->
        </div>

How can I get it to say, if no school object is returned, something along the lines of 'School not found, check your email'?

Thanks

like image 984
wtreston Avatar asked Feb 05 '18 10:02

wtreston


2 Answers

You need to perform validation on the form side. Implement clean_email method in the form:

def clean_email(self):
    email = self.cleaned_data.get('email')
    email = email.split('@')[1] 
    try:
       school = School.objects.get(email_domain = email)
    except ObjectDoesNotExist:
       raise forms.ValidationError(''School not found, check your email')
    return email

Now in template you can show this error right after email field:

 {{ form.email.label }}
 {{ form.email }}
 {{ form.email.errrors }}
 {{ form.email.help_text }}
like image 138
neverwalkaloner Avatar answered Oct 24 '22 18:10

neverwalkaloner


You can try Django's built-in messages framework. Try this:

try:
    school = School.objects.get(email_domain = email)
except ObjectDoesNotExist:
    messages.error(request, 'School not found, check your email')

And then somewhere above your form, add this:

{% if messages %}
    {% for message in messages %}
        <div class="alert {% if message.tags %} alert-{{ message.tags }}{% endif %}">{{ message|safe }}</div>
    {% endfor %}
{% endif %}

Hope it helps!

like image 31
Jahongir Rahmonov Avatar answered Oct 24 '22 19:10

Jahongir Rahmonov