You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django表单无空格输入时仍触发空格校验错误怎么解决?

问题原因

你的校验条件逻辑存在语法错误,当前写法:

if ' ' in poller_choice_one or poller_choice_two:

会被Python解析为两个独立判断的或运算:

  • 判断第一个字段是否包含空格:' ' in poller_choice_one
  • 直接判断第二个字段是否为非空值:poller_choice_two

只要用户填写了第二个字段,第二个判断结果就为真,整个if条件就成立,因此无论输入是否包含空格都会触发校验错误。

修复方案

修改校验条件,分别对两个字段做空格判断即可:

if ' ' in poller_choice_one or ' ' in poller_choice_two:
    raise ValidationError(('Limit your choice to one word'), code='invalid')
优化建议
  1. 字段校验逻辑更推荐放在Form类的clean方法中统一处理,符合Django的分层设计规范,示例如下:
from django import forms
from django.core.exceptions import ValidationError

class PollerForm(forms.Form):
    poller_choice_one = forms.CharField(label='Choice one', max_length=20, strip=True)
    poller_choice_two = forms.CharField(label='Choice two', max_length=20, strip=True)

    def clean(self):
        cleaned_data = super().clean()
        choice_one = cleaned_data.get('poller_choice_one')
        choice_two = cleaned_data.get('poller_choice_two')
        
        if choice_one and ' ' in choice_one:
            self.add_error('poller_choice_one', 'Limit your choice to one word')
        if choice_two and ' ' in choice_two:
            self.add_error('poller_choice_two', 'Limit your choice to one word')
        return cleaned_data
  1. 如果需要覆盖全角空格、制表符等所有空白字符,可以改用正则匹配判断:
import re
if re.search(r'\s', poller_choice_one) or re.search(r'\s', poller_choice_two):
    raise ValidationError('Limit your choice to one word', code='invalid')

内容的提问来源于stack exchange,提问作者JSRB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 09:51:00