我正在学习 django 1.8 (python 2.7.8),我正在尝试验证电子邮件,名字和姓氏字段。问题是我在表单中插入的内容会被保存到数据库中(仅限于默认电子邮件验证工作正常)。以下是我的表单,视图,模型和管理文件的样子。任何建议?谢谢
from django.db import models
# Create your models here.
class SignUp(models.Model):
email = models.EmailField()
first_name = models.CharField(max_length=25,blank=True,null=True)
last_name = models.CharField(max_length=25,blank=True,null=True)
timestamp = models.DateTimeField(auto_now_add=True,auto_now=False)
updated = models.DateTimeField(auto_now_add=False,auto_now=True)
def __unicode__(self):
return self.email
from django.contrib import admin
# Register your models here.
from .models import SignUp
class SignUpAdmin(admin.ModelAdmin):
list_display = ["__unicode__","first_name","last_name","timestamp","updated"]
class Meta:
model = SignUp
admin.site.register(SignUp, SignUpAdmin)
from django.shortcuts import render
from forms import SignUpForm
# Create your views here.
def home(request):
title = "Welcome"
form = SignUpForm(request.POST or None)
context = { "title": title,"form":form, }
if form.is_valid():
instance = form.save(commit=False)
instance.save()
return render(request, "home.html", context)
from django import forms
from .models import SignUp
import re
class SignUpForm(forms.ModelForm):
class Meta:
model = SignUp
fields = ['first_name','last_name','email']
def clean_email(self):
email = self.cleaned_data.get('email')
email_base, provider = email.split('@')
domain,extension = provider.split('.')
if provider.count('.') > 2: #email provider should not have more than 2 "dots=> ."
raise forms.ValidationError("Please use valid email address")
return email
def clean_first_name(self):
first_name = self.cleaned_data.get('first_name')
if bool(re.search('[\d\s]',first_name)): #firstname should not have whitespace or digits
raise forms.ValidationError("Please dont use numbers or space in Name Field")
return first_name
def clean_last_name(self):
last_name = self.cleaned_data.get('last_name')
if bool(re.search('[\d]',last_name)): #lastname should not have digits
raise forms.ValidationError("Please dont use numbers or space in Name Field")
return last_name
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$','newsletter.views.home', name='home'),
]
<html>
<title>Home Page</title>
<body>
{{ title }} {{ request.user }} <br>
<form method="post" action="">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit">
</form>
</body>
</html>
答案 0 :(得分:0)
你的form.py似乎很好。我认为你没有在HTML模板中显示错误
{%if form.errors%}
{%表示错误%。错误%}
{{errors}}
{%endfor%}
{%endif%}
答案 1 :(得分:0)