当有人在标题中提交带标点符号的内容时,我需要一种方法来引发错误。我是初学者,所以我不太清楚该怎么做 形式:
class NeededForm(forms.ModelForm):
title = forms.CharField(max_length=120)
likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
body = forms.CharField(min_length=50,widget = forms.Textarea)
captcha = CaptchaField()
def clean_title(self):
data = self.cleaned_data['title']
return data
class Meta:
model = Needed
fields = ('title', 'body', 'likes')
观点:
def detail(request, needed_title_url):
context = RequestContext(request)
needed_name = needed_title_url.replace('_', ' ')
context_dict = {'needed_name': needed_name}
try:
needed = Needed.objects.get(title=needed_name)
context_dict['needed'] = needed
print "True!"
except:
pass
return render_to_response('needed.html', context_dict, context)
如果用户输入类似:I like chicken!
的标题作为标题,那么我需要向用户显示错误。
答案 0 :(得分:1)
我不完全确定会提出您的问题,但看起来您正在寻找的答案可能会包含在https://docs.djangoproject.com/en/1.6/ref/models/fields/#slugfield
中SlugField 是 CharField ,它只能包含字母,数字,下划线和连字符(因此它理解 max_length ,...)
class NeededForm(forms.ModelForm):
title = forms.SlugField(max_length=120)
likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
body = forms.CharField(min_length=50,widget = forms.Textarea)
captcha = CaptchaField()
我正在寻找更复杂的规则检查,请查看验证器页面https://docs.djangoproject.com/en/1.6/ref/validators/以及如何以https://docs.djangoproject.com/en/1.6/ref/forms/validation/#using-validators形式使用它 提供的示例是解释 SlugField 实现。
希望它有所帮助!
答案 1 :(得分:0)
尝试此解决方案,确保标题中的每个单词仅包含字母,数字,短划线和撇号:
import string
def clean_title(self):
title = self.cleaned_data['title']
if all(letter not in string.punctuation
for word in title.split()
for letter in word
if letter not in ['-',"'"]):
return title
raise forms.ValidationError('Title cannot have punctuation')