【问题标题】:Django form widget: How can I set max value to a value on the database for each item?Django 表单小部件:如何将最大值设置为每个项目的数据库值?
【发布时间】:2021-06-20 15:57:22
【问题描述】:
class CustomerOrderForm(ModelForm):
quantity = forms.IntegerField(widget=forms.TextInput(attrs={'min':0,'max':,'value':0,'type':'number','style':'max-width: 3em'}))
class Meta: 
    model = Cart
    fields = ('__all__')

每个项目都有自己的购买限制,所以我想去数据库并获取该项目的购买限制并将其设置为“最大值”。如何在 django 表单上执行此操作?

我知道html,是这样的,但我有一个动态值需要从数据库中获取:

label for="zip_code">Zip Code:</label>
    <input type="text" id="zip_code" name="zip_code" placeholder="Five digit zip code" pattern="[0-9]{5}" maxlength="5" required>

【问题讨论】:

  • 只需在模型对象的视图中将值作为上下文传递,然后在 html 表单中执行 maxlength={{context}}。
  • 这对小部件不起作用...我收到一条错误消息:quantity = forms.IntegerField(widget=forms.TextInput(attrs={'min':0,'max': {{ item.limit }},'value':0,'type':'number','style':'max-width: 3em'})) NameError: name 'item' is not defined
  • 不在小部件中,在模板的 HTML 中。

标签: django forms widget


【解决方案1】:

您必须在 init 函数中设置/更新您的最大值,因为您的最大值取决于一个实例。像这样的。

class CustomerOrderForm(ModelForm):
    quantity = forms.IntegerField(widget=forms.TextInput(attrs={'min':0, 'value':0,'type':'number','style':'max-width: 3em'}))
    class Meta: 
    model = Cart
    fields = ('__all__')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['quantity'].widget.attrs.update(
            {'max': self.instance.quantity},
        )

请注意,此检查仅在渲染 HTML 时在 init 中进行。提交表单时,您可能希望在 clean() 或 save() 函数中进行一些验证。

编辑: 我没有正确阅读您的问题。

self.instance

指的是购物车模型。但您可能想要迭代您的项目。

【讨论】:

猜你喜欢
  • 2019-07-30
  • 1970-01-01
  • 2016-04-07
  • 1970-01-01
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多