我无法让我的验证显示出来。首先,我想知道这些验证是否应该在models.py或forms.py中完成?
通过研究,我发现您可以使用cleaning_data和验证逻辑创建验证。我还发现了一个可以在模型中使用的称为验证器的东西 - 也许还有modelForm?
以下是我编写的一些代码,我在视图中看不到验证。任何帮助将不胜感激。
class ServiceForm(forms.ModelForm):
category= forms.ChoiceField(choices= CATEGORIES)
service_description= forms.CharField(widget=forms.Textarea)
more_service_info= forms.CharField(widget=forms.Textarea)
class Meta:
model = Service
fields = ('service_name', 'category', 'address', 'city', 'state', 'zipcode',
'phone', 'website_link', 'service_description', 'more_service_info',
'price', 'pub_date',)
def clean_service_description(self):
data = self.cleaned_data['service_description']
if len(data) < 10:
raise forms.ValidationError("Description should be greater than 10 characters")
return data
编辑这是我的观看代码
def create(request):
if request.POST:
form= ServiceForm(request.POST)
if form.is_valid():
service_obj = form.save(commit=False)
service_obj.user_id = request.user.id
service_obj.save()
return render_to_response('services/service_created.html',
{'service': Service.objects.get(id=service_obj.id)})
else:
form = ServiceForm()
args= {}
args.update(csrf(request))
args['form'] = form
return render_to_response('services/create_service.html', args )