簡體   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