imlearningdjango1.8(python2.7.8),我试图验证email、firstname和lastname场。那个问题是我插入表单的内容都会保存到数据库中(只有默认的电子邮件验证有效)。下面是我的表单,视图,模型和管理文件的外观就像。任何人建议?谢谢你
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.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>
你的表单.py看起来不错。我想你没有在模板HTML中显示错误。
{%如果表格错误%}
{%中的错误表格错误%}
{{errors}}
{%endfor%}
{%endif%}
我犯了一些愚蠢的错误(缩进)。问题已更正,编码正确
相关问题 更多 >
编程相关推荐