我有一个注册表单,用于验证电子邮件字段是否包含gmail,如果不包含,则会给出错误。
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})
我想添加一些其他"受信任的电子邮件",这样表单将允许用户注册,例如:@yahoo.com、@outlook.com,但我无法添加列表或元组,因为我收到了一个错误:
TypeError at /signup/
'in <string>' requires string as left operand, not tuple
问题如何创建受信任的电子邮件域列表,而不是"@gmail.com"放置电子邮件域列表?
您可以创建一个受信任的电子邮件服务的list
,并检查您的submitted_data
,即在您的情况下,email
包含任何电子邮件服务。你可以试试这个。
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')
从错误中,您似乎正在尝试执行以下操作:if ['a', 'b'] in 'string'
?我相信in
只能检查左边的单个项是否在右边的迭代器中。因此,要想做到这一点,你必须在in
的左边有一个项目,而不是一个列表。
你试过这样的东西吗?
if not any(email in submitted_data for email in ['@gmail.com', '@otheremail.com']):
raise YourError