cleaning_data在django 1.8.6中不起作用

时间:2015-11-18 09:05:06

标签: python django forms

我正在研究django教程,并尝试使用cleaning_data属性验证表单。

forms.py文件的代码是

 from django import forms
 from .models import SignUp

 class SignUpForm(forms.ModelForm):

        class Meta:
            model = SignUp
            fields = ['email']

        def clean_email(self):
            email = self.cleaned_data.get('email')
            if not '.edu' in email: 
                raise forms.ValidationError('Please use a valid academic email address')
            print(email)
            return email

models.py文件包含以下代码

from django.db import models

# Create your models here.
class SignUp(models.Model):
    email = models.EmailField()
    full_name = models.CharField(max_length=255)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __str__(self):
        return self.email

并且admin.py具有以下代码行

from django.contrib import admin
from .models import SignUp
from .forms import SignUpForm

class SignUpAdmin(admin.ModelAdmin):
    list_display = ['full_name', 'email', 'timestamp', 'updated']
    class Meta:
        form = SignUpForm

admin.site.register(SignUp, SignUpAdmin)

我得到的问题是,无法抓取电子邮件字段并且无法处理电子邮件字段,事实上cleaning_data不包含数据,print(email)不在控制台中打印电子邮件。我无法验证.edu电子邮件地址

我正在使用python3和django1.8.6

1 个答案:

答案 0 :(得分:2)

您已将管理类定义错误,因此未使用自定义表单。你没有在modeladmin中使用class Meta;你只需要直接定义类属性。

class SignUpAdmin(admin.ModelAdmin):
    list_display = ['full_name', 'email', 'timestamp', 'updated']
    form = SignUpForm