django表单验证基于字段是否具有值 [英] django form validation based on whether field has value
问题描述
-
当我提交一个空格式,选择一个
phone_type
(对于formHomePhone
)表单返回自己,而没有在phone_type
中选择的值,规定此字段为必需
When I submit an empty form with a
phone_type
selected (forformHomePhone
) the form returns its self without a value selected inphone_type
stipulatingThis field is required
从视图中可以看到窗体中的第一个电话号码是必需的,但其他电话号码不是。如果存在值,我只想处理它们。虽然当我点击提交一个空的表单时,额外的电话号码字段从 UKPhoneNumberField
> 中引发错误电话号码必须包含一个区号。 / code>如果在尊敬的字段中有一个数字,我该如何验证?
As you can see from the view The first phone number in the form is required but the other phone numbers are not. I only want to process them if there is a value present. Though when I click submit on an empty form the additional phone number fields throw up an error from the UKPhoneNumberField
> Phone number must include an area code.
How can I only validate when there is a number in the respected field?
我有一个这样的view.py文件
I have a view.py file like this
def new_client_view(request):
if request.method == 'POST':
formDetails = ClientDetailsForm(request.POST)
formAddress = ClientAddressForm(request.POST)
formHomePhone = ClientPhoneForm(request.POST)
formWorkPhone = ClientOtherPhoneForm(request.POST)
formMobilePhone = ClientOtherPhoneForm(request.POST)
if formDetails.is_valid() and formAddress.is_valid() and formHomePhone.is_valid():
c = Client()
c.save()
fd = formDetails.save(commit=False)
fd.client = c
fd.created_by = request.user
fd.save()
fa = formAddress.save(commit=False)
fa.client = c
fa.created_by = request.user
fa.save()
fph = formHomePhone.save(commit=False)
fph.client = c
fph.created_by = request.user
fph.save()
if 'p2-number' in request.POST and request.POST['p2-number']:
fpw = formWorkPhone.save(commit=False)
fpw.client = c.id
fpw.created_by = request.user
if fpw.is_valid():
fpw.save()
if 'p3-number' in request.POST and request.POST['p3-number']:
fpm = formMobilePhone.save(commit=False)
fpm.client = c
fpm.created_by = request.user
if fpm.is_valid():
fpm.save()
return render_to_response('client/client.html', context_instance=RequestContext(request))
else:
return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))
else:
formAddress = ClientAddressForm()
formDetails = ClientDetailsForm()
formHomePhone = ClientPhoneForm(initial={'phone_type':'home'}, prefix="p1")
formWorkPhone = ClientPhoneForm(initial={'phone_type':'work'}, prefix="p2")
formMobilePhone = ClientPhoneForm(initial={'phone_type':'mobi'}, prefix="p3")
return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))
一个forms.py像这样:
a forms.py like this:
class ClientDetailsForm(ModelForm):
class Meta:
model = ClientDetails
exclude = ('client', 'created', 'created_by')
class ClientAddressForm(ModelForm):
class Meta:
model = ClientAddress
exclude = ('client', 'created', 'created_by')
class ClientPhoneForm(ModelForm):
number = UKPhoneNumberField()
class Meta:
model = ClientPhone
exclude = ('client', 'created', 'created_by')
class ClientOtherPhoneForm(ModelForm):
number = UKPhoneNumberField(required=False)
class Meta:
model = ClientPhone
exclude = ('client', 'created', 'created_by')
和一个models.py,如下所示:
and a models.py like this:
MARITAL_STATUS_CHOICES = (
...
)
NAME_TITLE_CHOICES = (
...
)
PHONE_CHOICES = (
('home', 'Home'),
('home2', 'Home 2'),
('mobi', 'Mobile'),
('mobi2', 'Mobile 2'),
('work', 'Work'),
('work2', 'Work 2'),
)
class Client(models.Model):
closed = models.DateTimeField(blank=True, null=True)
closed_by = models.ForeignKey(User, blank=True, null=True)
comment = models.TextField(blank=True, null=True)
def __unicode__(self):
return u'%s' % (self.id)
class ClientDetails(models.Model):
...
class ClientAddress(models.Model):
...
class ClientPhone(models.Model):
client = models.ForeignKey(Client, null=True)
created = models.DateTimeField(default=datetime.now)
created_by = models.ForeignKey(User, blank=True, null=True)
phone_type = models.CharField(max_length=5, choices=PHONE_CHOICES)
number = models.CharField(max_length=24)
BTW我的 new_client_view
函数不是很干,我知道。任何建议将被感激地收到)
BTW(my new_client_view
function is not very DRY I know. Any recommendations would be gratefully received)
推荐答案
我发现一个这样的答案(是的,我知道这是愚蠢!)
I found an answer that goes something like this (yes I know it's stupid!)
def new_client_view(request):
if request.method == 'POST':
formDetails = ClientDetailsForm(request.POST)
formAddress = ClientAddressForm(request.POST)
formHomePhone = ClientPhoneForm(request.POST)
if formDetails.is_valid() and formAddress.is_valid() and formHomePhone.is_valid():
c = Client()
c.save()
fd = formDetails.save(commit=False)
fd.client = c
fd.created_by = request.user
fd.save()
fa = formAddress.save(commit=False)
fa.client = c
fa.created_by = request.user
fa.save()
fph = formHomePhone.save(commit=False)
fph.client = c
fph.created_by = request.user
fph.save()
if 'p2-number' in request.POST and request.POST['p2-number']:
formWorkPhone = ClientOtherPhoneForm(request.POST)
fpw = formWorkPhone.save(commit=False)
fpw.client = c.id
fpw.created_by = request.user
# if the work number is valid
if fpw.is_valid():
# check the mobile number before you save the work number
if 'p3-number' in request.POST and request.POST['p3-number']:
formMobilePhone = ClientOtherPhoneForm(request.POST)
fpm = formMobilePhone.save(commit=False)
fpm.client = c
fpm.created_by = request.user
# if the mobile number is good then there is no more checking to do
if fpm.is_valid():
fpm.save()
# else load up the form again with the error for the mobile phone and the original
# data for the mobile phone and the work phone
else:
formWorkPhone = ClientOtherPhoneForm(request.POST)
return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))
# if the work number is valid and the mobile field wasn't used then just save the work number
fpw.save()
# if the work number is not valid then find out if a mobile number
# was entered and feed it back to the form
else:
if 'p3-number' in request.POST and request.POST['p3-number']:
formMobilePhone = ClientOtherPhoneForm(request.POST)
else:
formMobilePhone = ClientPhoneForm(initial={'phone_type':'mobi'}, prefix="p3")
return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))
return render_to_response('client/client.html', context_instance=RequestContext(request))
# if the form doesn't validate then you need to find out if the optional fields contain data,
# and if so load that data back into the form
else:
if 'p2-number' in request.POST and request.POST['p2-number']:
formWorkPhone = ClientOtherPhoneForm(request.POST, prefix="p2")
else:
formWorkPhone = ClientPhoneForm(initial={'phone_type':'work'}, prefix="p2")
if 'p3-number' in request.POST and request.POST['p3-number']:
formMobilePhone = ClientOtherPhoneForm(request.POST, prefix="p3")
else:
formMobilePhone = ClientPhoneForm(initial={'phone_type':'mobi'}, prefix="p3")
return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))
else:
formAddress = ClientAddressForm()
formDetails = ClientDetailsForm()
formHomePhone = ClientPhoneForm(initial={'phone_type':'home'}, prefix="p1")
formWorkPhone = ClientPhoneForm(initial={'phone_type':'work'}, prefix="p2")
formMobilePhone = ClientPhoneForm(initial={'phone_type':'mobi'}, prefix="p3")
return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))
我想我需要覆盖窗体上的 is_valid
函数,以确保其中一个字段中有数据在执行类似 super.is_valid()
之前(否则返回true,所以我不会为空表单引发错误),还有一个在
函数d。将它们放入字段,然后检查是否有保存前的电话号码。用户
和客户端
对象的表单上保存
I think I need to overwrite the is_valid
function on the form to make sure there is data in one of the fields before doing something like super.is_valid()
(else returning true so I don't raise an error for an empty form) and also a pre-save
function on the form that takes the user
and client
objects and puts them into the fields and checks there is a phone number before saving.
- 覆盖
is_valid()
以确保空白值可以通过 - 创建
预先保存()
以用户
和客户端
到模型中,如果可以,如果没有数字
- Overwrite
is_valid()
to make sure blank values can get through - Create
pre-save()
to load inUser
andClient
into the model and abort if you can if there is no value fornumber
这是CRAZY !!!
我可以想到的唯一其他事情是在 phone_type
和号码
> ClientPhone model blank = True,null = True
,以便我可以选择电话字段
The only other thing I can think of is making phone_type
and number
in the ClientPhone
model blank=True, null=True
so that I can have optional phone fields
CRAZY AS WELL !!!
为什么我必须打破我的模型的完整性只是为了有一个选项字段我的一种形式?
Why should I have to break the integrity of my model just to have an option field in one of my forms???
当我对forms.py文件进行以下操作时,view.py变得更干净:
view.py turned out cleaner when I did the following to the forms.py file:
class ClientDetailsForm(ModelForm):
class Meta:
model = ClientDetails
exclude = ('client', 'created', 'created_by')
def CustomSave(self,c,u):
t = self.save(commit=False)
t.client = c
t.created_by = u
t.first_name = self.cleaned_data['first_name'].capitalize()
t.middle_name = self.cleaned_data['first_name'].capitalize()
t.last_name = self.cleaned_data['first_name'].capitalize()
t.save()
class ClientAddressForm(ModelForm):
class Meta:
model = ClientAddress
exclude = ('client', 'created', 'created_by')
def CustomSave(self,c,u):
t = self.save(commit=False)
t.client = c
t.created_by = u
t.address_1 = self.cleaned_data['address_1'].capitalize()
t.address_2 = self.cleaned_data['address_2'].capitalize()
t.address_3 = self.cleaned_data['address_3'].capitalize()
t.address_4 = self.cleaned_data['address_4'].capitalize()
t.post_code = self.cleaned_data['post_code'].upper()
t.save()
class ClientPhoneForm(ModelForm):
number = UKPhoneNumberField()
class Meta:
model = ClientPhone
exclude = ('client', 'created', 'created_by')
def CustomSave(self,c,u):
t = self.save(commit=False)
t.client = c
t.created_by = u
t.save()
class ClientOtherPhoneForm(ModelForm):
number = UKPhoneNumberField(required=False)
class Meta:
model = ClientPhone
exclude = ('client', 'created', 'created_by')
def CustomSave(self,c,u):
t = self.save(commit=False)
t.client = c
t.created_by = u
t.save()
这篇关于django表单验证基于字段是否具有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!