0

I want to have an email check in my email form field so that if the user's email doesn't end with '@aun.edu.ng' it will through an error message.

forms.py

class EmployeeRegistrationForm(forms.ModelForm):
    first_name = forms.CharField(label='First Name')
    last_name = forms.CharField(label='Last Name')
    cv = forms.FileField(label='CV')
    skills_or_trainings = forms.SlugField(label='Skills or Trainings', required=False, widget=forms.Textarea)
    class Meta:
        model = Student
        fields = ['first_name', 'last_name', 'gender', 'level', 'school', 'major', 'cv', 'skills_or_trainings' ]



class EmployerRegistrationForm(forms.ModelForm):
    company_name = forms.CharField(label="Company Name")
    company_address = forms.CharField(label="Company Address")
    website = forms.CharField()

    class Meta:
        model = Employer
        fields = ['company_name', 'company_address', 'website']

views.py

def student_register(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        student_form = EmployeeRegistrationForm(request.POST)

        if form.is_valid() and student_form.is_valid():
            user = form.save(commit=False)
            user.is_student = True
            user.save()

            student = student_form.save(commit=False)
            student.user = user
            student.save()
            return redirect('login')
    else:
        form = UserRegistrationForm()
        student_form = EmployeeRegistrationForm()
    
    context = {'form': form, 'student_form': student_form}
    return render (request, 'accounts/employee/register.html', context)

def employer_register(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        employer_form = EmployerRegistrationForm(request.POST)

        if form.is_valid() and employer_form.is_valid():
            user = form.save(commit=False)
            user.is_employer = True
            user.save()

            employer = employer_form.save(commit=False)
            employer.user = user
            employer.save()
            return redirect('login')
    else:
        form = UserRegistrationForm()
        employer_form = EmployerRegistrationForm()
    
    context = {'form': form, 'employer_form': employer_form}
    return render (request, 'accounts/employer/register.html', context)

Please how do I go about it so that I will be able to through a Validation Error message when the user puts in an email that doesn't end with '@aun.edu.ng' Thank you

Daniel
  • 1
  • 2

2 Answers2

1

To raise validation error for the employer you can do this by overriding the clean() method of the EmployerRegistrationForm form.

from django.form import ValidationError

class EmployerRegistrationForm(forms.ModelForm):
    company_name = forms.CharField(label="Company Name")
    company_address = forms.CharField(label="Company Address")
    website = forms.CharField()

    class Meta:
        model = Employer
        fields = ['company_name', 'company_address', 'website']
    
    def clean(self):
        cleaned_data = super().clean()
        if cleaned_data.get('company_address').endswith('@aun.edu.ng'):
            raise ValidationError('This email is not applicable')
        return cleaned_data 
Lewis
  • 2,718
  • 1
  • 11
  • 28
  • Can I raise validation error for only the email which would be registered under the student email? – Daniel Aug 20 '20 at 11:59
  • Yes you can, except from what you have provided their is no email field in the `EmployeeRegistrationForm`. – Lewis Aug 20 '20 at 12:06
  • The email field is a general field for all the models so I put it in the User Model. So would it be possible to restrict the validation to only students? – Daniel Aug 20 '20 at 12:34
0

See this answer for a regular expression that matches email addresses. You can use this in Python with the regular expression module. If the email is invalid, just send them back to the login with a message saying the email address is invalid.

import re

email_re = """(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])"""

if re.match(email_re, "someone@example.com"):
    print("Match found")
else:
    print("Invalid email address")

Please note that valid email addresses include unregistered email addresses and the only way to verify an email address completely is to send them an email with a verification link. This link would then allow them to "unlock" the account created.

The Otterlord
  • 1,680
  • 10
  • 20
  • So I will put the allowed letters in the email_re? And how do I go about sending the email verification link – Daniel Aug 20 '20 at 09:46
  • I want the email validation to be for the student model only, then maybe the verification link can be sent to all models. How do I go about that? – Daniel Aug 20 '20 at 09:47
  • Apart from the regex method, is there another way I could go about it? – Daniel Aug 20 '20 at 09:48
  • ``` import re email_re = """(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])""" if re.match(email_re, "someone@aun.edu.ng"): print("Match found") else: print("Invalid email address")``` – Daniel Aug 20 '20 at 09:49
  • So would that be what I will write in my views.py or forms.py – Daniel Aug 20 '20 at 09:51
  • It would go in whatever file uses `re` and `email_re` (probably the one with `.is_valid` function). You could also split it up into the prefix, the @ and the suffix (domain) and check that works. If you want if for the student one only, then just perform the validation on that. To create a verification email, create a unique link and email it to that address. The account could be locked until that link is visited. – The Otterlord Aug 20 '20 at 12:20