【问题标题】:None error when comparing words using the lenght of themselves使用自身长度比较单词时没有错误
【发布时间】:2020-11-16 14:17:01
【问题描述】:

我正在尝试使用Otree 对主题可以在表单字段中使用的最少字符数进行限制。我希望如果受试者输入的名称长度少于 4 个字符,应用程序会向他们显示一个错误,说明他们必须写一个更长的单词。

我正在使用len,但出现以下错误:

'NoneType' has no len()

谁能帮我找出代码中的问题并帮我修复它?

这是我的 pages.py 代码。


class Consentimiento(Page):

    form_model = 'player'
    form_fields = ['consentimiento', 'consentimienton',]

    def consentimiento_error_message(self, value):
        print('El nombre es', value)
        if len(self.player.consentimiento)) < Constants.number:
            return 'Por favor en el campo de nombre debe poner mínimo 4 letras'
 

这是我的 models.py 代码

consentimienton =  models.StringField( max_length=50 )

【问题讨论】:

  • 这是什么? self.player.consentimiento 另外,consentimiento 和 consentimienton 很容易混合
  • self.player.consentimiento 是一个空的字符串字段,人们在其中输入他们的姓名。
  • 你确定它是stringField类型的吗?尝试打印出self.player.consentimiento的类型,然后检查是否是len()的兼容类型
  • 是的,我在models.py中定义了

标签: python otree


【解决方案1】:

我注意到您的工作示例中有几个错误。

  • len(self.player.consentimiento) 正在检查数据,而不是用户提供的输入。您应该将其替换为len(value)。 (还要注意额外的括号)

  • 您正在使用fieldname_error_message(self,value) 函数。这应该被定义:

    • 用于字段,而不用于页面。
    • 在您的模型下的models.py,而不是pages.py

所以最后你应该在models.py中有以下内容:

# Don't forget to define number field in Constants

class Player(BasePlayer):
    consentimienton =  models.StringField( max_length=50 )

    def consentimienton_error_message(self, value):
        print('El nombre es', value)
        if len(value) < Constants.number:
            return 'Por favor en el campo de nombre debe poner mínimo 4 letras'


这个在你的pages.py:

class Consentimiento(Page):
    form_model = 'player'
    form_fields = ['consentimienton']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 2020-07-03
    • 1970-01-01
    • 2012-02-13
    相关资源
    最近更新 更多