Home > front end >  Django, Create domain block list for sign up
Django, Create domain block list for sign up

Time:03-01

I am trying to create domain block list for my sign up form and I am having an issue. I made table for domain block list and I want sign up form to raise error if domain is in block list. Apparently, my code doesn't work unless I hardcode it. How do I make this work? :(

forms.py

class MyCustomSignupForm(SignupForm):
    first_name = forms.CharField(max_length=30, label='First Name')
    last_name = forms.CharField(max_length=30, label='Last Name')
    company_name = forms.CharField(max_length=50, label='Comapny Name')


    class Meta:
        model = DomainBlock
        fields = ('blocklist')

## block common domain from sign up
    def clean_email(self):
        data = self.cleaned_data['email']

        if data.split('@')[1].lower() in 'blocklist':
            raise forms.ValidationError("This email is not allowed")
        # if data.split('@')[1].lower() == 'gmail.com':
        #     raise forms.ValidationError("Gmail is not allowed")
        # if data.split('@')[1].lower() == 'msn.com':
        #     raise forms.ValidationError("MSN email is not allowed")
        # if data.split('@')[1].lower() == 'yahoo.com':
        #     raise forms.ValidationError("Yahoo email is not allowed")
        return data

model.py

class DomainBlock(models.Model):

    domain_id = models.AutoField(primary_key=True)
    blocklist = models.CharField('Domain Block List', max_length=50, null=True, blank=True)

CodePudding user response:

Query your DomainBlock model in the clean method

def clean_email(self):
    data = self.cleaned_data['email']

    if DomainBlock.objects.filter(blocklist=data.split('@')[1].lower()).exists():
        raise forms.ValidationError("This email is not allowed")
    return data
  • Related