繁体   English   中英

Django 表单 - 具有数字范围的 ChoiceField

[英]Django forms - ChoiceField with range of numbers

class House(models.Model):
    floors = IntegerField()  # 10 floors for example

class Flat(models.Model):
    floor = IntegerField(null=True, validators=[MinValueValidator(1)])  # then here should be from 1 to 10 or None
    house = ForeignKey(House)

class FlatForm(models.ModelForm):
    class Meta:
        model = Flat
        fields = ['floor']
        widgets = {'floor': .....}  # I don't know what to do here. Select widget?

你好。 任何提示我如何实施一种表格,我可以在房子的楼层数内为公寓选择一层?


我通过 Select2 和 API 进行了动态选择上传。

根据Django docs ,应该执行以下操作:

class House(models.Model):
    Floor = models.IntegerChoices('Floor', range(1,11))
    floors = IntegerField(choices=Floor.choices)

(我现在无法测试 - 也许你需要list(range(1,11)) 。)

我认为您不需要更改表单中的小部件的任何内容,除非您对默认小部件不满意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM