如何将类的实例设置为小部件形式的下拉列表

时间:2019-04-16 21:33:03

标签: django forms choicefield

我尝试在模板中使用来自数据库的对象作为选择列表。我发现我可以使用小部件form.select并从数据库中设置对象的选择,但是我希望通过一些for循环手动进行此操作?

forms.py

'''     从django.forms导入ModelForm     从Django导入表格     从.models import船

class ShipForm(ModelForm):

    class Meta:
        model = Ship
        fields = ['name','rolls','rolls_del']
        all_instance = Ship.objects.all()
        INSTANCE_CHOICES = (('1111','1111'),('333','333'), 
('11','11'))
        widgets = {'name':forms.Select(choices=INSTANCE_CHOICES)}

'''

在这里,在INSTANCE_CHOICES中,我想要一些for循环或一些自动填写的方法

models.py

'''     从django.db导入模型     从django.forms导入ModelForm

class Ship(models.Model):
    name = models.CharField(max_length = 20)
    rolls = models.IntegerField(null = True)
    rolls_del = models.IntegerField(default=0)
    total = models.IntegerField(default=0)


    def __str__(self):
        return self.name

''' views.py

'''

def data(request):
    ships = Ship.objects.all().order_by('name')
    for x in ships:
        x.total = x.rolls - x.rolls_del
    cont = {'ships':ships}
    return render(request,'data.html', context=cont)

'''

0 个答案:

没有答案