自定义验证在Forms.py中不起作用

时间:2019-02-19 07:04:06

标签: django python-3.x

我想验证我的电子邮件字段,例如:如果电子邮件包含[gmail.com,outlook.com,yahoo.com],那么我想提出验证错误。但这不起作用,我不知道我在做什么错。请帮助我

views.py

from django.shortcuts import render
from django.views.generic import View
from access.utils import is_valid
from access.mixin import HttpResponseMixin
import json
from access.forms import Employer_Form
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

@method_decorator(csrf_exempt,name = 'dispatch')
class Emp_Registration_view(View,HttpResponseMixin):
  def post (self,request,*args,**kwargs):
    data = request.body
    json_data = is_valid(data)
    if not json_data:
        return self.render_http_response(json.dumps({'msg':'Please send valid json only'}),status=400)
    emp_data = json.loads(data)
    form= Employer_Form(emp_data)
    if form.is_valid():
        form.save(commit=True)
        return self.render_http_response(json.dumps({'msg':'Registered Successfully'}))
    if form.errors:
        return self.render_http_response(json.dumps(form.errors),status=400)

forms.py

from access.models import Employer_Registration
from django import forms

class Employer_Form(forms.ModelForm):
  def clean_email(self):
    email = self.cleaned_data['emp_email']
    email_lists = ['gmail.com','yahoo.com','outlook.com','hotmail.com']
    data = emp_email.split('@')
    if data in email_lists:
        raise forms.ValidationError("email is not valid")
    return email

  class Meta:
    model = Employer_Registration
    fields = '__all__'

2 个答案:

答案 0 :(得分:3)

您的方法应命名为clean_emp_email,因为该字段命名为emp_email。否则它将不会被调用。

答案 1 :(得分:0)

好像您正在@上进行拆分,因此如果您拆分example@gmail.com,它将是[example , gmail.com],并且您正在此行中进行精确的比较

if [example , gmail.com] in email_lists

所以找不到它,我建议您做一下,您可以省略分割并在子字符串中找到

for i in email_lists:
    if i in self.cleaned_data['emp_email']:
       raise forms.ValidationError("email is not valid")

在@Alexandr Tatarinov回答后,您还应该致电clean_field_name或简称为clean