I have a signup form that verifies if the email field contains gmail and gives an error if not.
forms.py
def clean_email(self):
submitted_data = self.cleaned_data['email']
if '@gmail.com' not in submitted_data:
raise forms.ValidationError('You must register using a gmail address')
views.py
class SignUpView(View):
form_class = SignUpForm
template_name = 'user/register.html'
def get(self, request, *args, **kwargs):
form = self.form_class()
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False # Deactivate account till it is confirmed
user.save()
current_site = get_current_site(request)
subject = 'Activate Your Account'
message = render_to_string('user/account_activation_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
user.email_user(subject, message)
return redirect('confirm_registration')
return render(request, self.template_name, {'form': form})
I want to add few other 'trusted emails' so the form will allow users to register for instance: @yahoo.com, @outlook.com but I cannot add a list or tuple because I get an error:
TypeError at /signup/
'in <string>' requires string as left operand, not tuple
Question How can I create a list of trusted email domains and instead '@gmail.com' put list of email domains?
CodePudding user response:
From the error, it looks like you are trying to do something like:
if ['a', 'b'] in 'string'
? I believe in
can only check if a single item on the left is in an iterator on the right.
So for this to work you would have to have a single item on the left of your in
rather than a list.
Have you tried something like this?
if not any(['@gmail.com', '@otheremail.com'] in submitted_data):
raise YourError
CodePudding user response:
You can make a list
of trusted email services and check for your submitted_data
i.e. email
in your case contains any of the email services. You can try this.
def clean_email(self):
submitted_data = self.cleaned_data['email']
trusted_email_services = ["@gmail.com", "@yahoo.com", "@outlook.com"]
if not any(email_service in submitted_data for email_service in trusted_email_services)
raise forms.ValidationError('You must register using a gmail or yahoo or outlook address')