Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 如果用户在Django的表单字段中只输入空格,那么捕获和显示错误的最佳方法是什么?_Regex_Django_Validation_Forms_Field - Fatal编程技术网

Regex 如果用户在Django的表单字段中只输入空格,那么捕获和显示错误的最佳方法是什么?

Regex 如果用户在Django的表单字段中只输入空格,那么捕获和显示错误的最佳方法是什么?,regex,django,validation,forms,field,Regex,Django,Validation,Forms,Field,在Django 1.0中,如果用户在表单字段中只输入空格(“”),那么捕获和显示错误的最佳方法是什么 class Item(models.Model): description = models.CharField(max_length=100) class ItemForm(ModelForm): class Meta: model = Item 若用户在description CharField中只输入空格(“”),那个么需要对类Item或类ItemFor

在Django 1.0中,如果用户在表单字段中只输入空格(“”),那么捕获和显示错误的最佳方法是什么

class Item(models.Model):
    description = models.CharField(max_length=100)

class ItemForm(ModelForm):
    class Meta:
        model = Item
若用户在description CharField中只输入空格(“”),那个么需要对类Item或类ItemForm做什么更改,以使form.is_valid()失败并显示错误

在form.is_valid()之后,我可以编写代码,只检查description字段中的空格,并引发验证错误,但必须有更好的方法。RegexField可用于指定输入的描述,而不应仅为空白。有什么建议吗

class ItemForm(forms.ModelForm):
    class Meta:
        model = Item

    def clean_description(self):
        if not self.cleaned_data['description'].strip():
            raise forms.ValidationError('Your error message here')

这本书也许能提供一个很好的读物。

找到了答案。只需将description=forms.RegexField(regex=r'[^(\s+)]')添加到类ItemForm中,就会导致表单.is\u valid()失败并显示错误

class ItemForm(ModelForm):
    description = forms.RegexField(regex=r'[^(\s+)]')
    class Meta:
        model = Item
要包含您自己的消息,请添加错误消息=。。。到forms.RegexField

description = forms.RegexField(regex=r'[^(\s+)]', error_message=_("Your error message here."))

为什么是正则表达式?只需使用
str.strip()
检查字符串是否仅由空格组成,Carl,感谢您给出答案。我在课堂上发布了一个简短的单行更新,解决了这个问题。我对modelform不够熟悉,无法了解RegexField在这种情况下如何工作。询问django irc并再次阅读,将其排序。