首页 文章

django python动态max_length基于选择列表值

提问于
浏览
0

我正在使用django 1.7和python 2.7 .

我有一个模型类,允许用户输入文本区域和文本框 .

If 用户在选择列表中选择0, then 文本框显示给用户输入,文本区域隐藏 else 显示文本区域,文本框隐藏用户 .

文本框和文本区域都具有完全相同的输入 . 输入到文本框的内容将出现在文本区域,反之亦然 .

文本框和文本区域都具有不同的maxlength / max_length值 .

文本框的最大长度为250,文本区域的最大长度为5000 .

我有客户端验证工作,但我很难让服务器端验证工作 .

How do I enable / disable the server side validation to my model on the forms.py file when the text box and text area have different max_length values, but the same input lengths?

我知道可以在forms.py上分配max_length,但我无法使代码语法正确 .

这是我的models.py代码:

workplace_training_display_type = models.PositiveIntegerField(.....)
workplace_training_certificationTB = models.CharField(null=False, blank=False)
workplace_training_certificationTA = models.TextField(null=False, blank=False)

通常我会在上面的模型字段中将 max_length=250 放到 workplace_training_certificationTBmax_length=5000workplace_training_certificationTA . 但是,我认为这必须在forms.py文件中动态完成 .

EDIT 如果我将max_length设置为 workplace_training_certificationTBworkplace_training_certificationTA 的模型,因为两个字段具有完全相同的输入,那么将触发一个服务器端验证,这就是我想动态设置值的原因 .

这是我的forms.py文件代码:

def clean(self):

    cd_wrtdf = super(WorkplaceRelatedTrainingDetailsForm, self).clean()

    if 'workplace_training_display_type' in cd_wrtdf and cd_wrtdf['workplace_training_display_type'] != 0:

        #  if the workplace_training_display_type is not zero, remove the max_length=250 from the textbox.

        #  if the workplace_training_display_type is not zero, add the max_length=5000 to the textarea.

    else:

        #  if the workplace_training_display_type is zero, add the max_length=250 to the textbox.

        #  if the workplace_training_display_type is zero, remove the max_length=5000 from the textarea.

    return cd_wrtdf

我试过搜索SO和Google,但找不到任何有用的东西 .

2 回答

  • 1

    在您的模型上具有重复字段并不是实现此目的的正确方法 . 您应该将模型更改为只有一个字段,文本字段,最大长度为5000.然后在forms.py中,您可以使用 len(input) 检查输入的长度 . 然后,您可以根据其他所选字段确定它是否在限制范围内 .

    在你的干净方法中,调用 super() 将自动检查它是否在5000以内,然后你只需检查它是否需要小于250.如果是,那么只需查看 if len(input) > 250: raise ValidationError('Too long for type') .

  • 2

    模型字段中不能有动态长度,因为这些是在数据库级别实现的 . 在字段上设置最大长度时,它会将其转换为等效的SQL,这将限制可以存储在数据库级别的数据量 .

    正如@electrometro所提到的,我还建议你的模型中有一个长度为5000的CharField .

    由于这似乎更像是一个用户界面问题,您应该使用Javascript执行此操作,并根据您提到的用户选择替换所需类型的输入 . 只要表单输入发布具有相同名称的数据,Django表单仍将按预期运行 .

    您可以执行与this toggle behavior类似的操作,但当用户从列表中选择一个选项时,您将触发它 . 还要确保输入/ textarea ID和名称与表单字段相同,以便表单可以清理数据 .

相关问题