[英]Django populating a choice field
I am working with four tables: 我正在使用四个表:
class Product(models.Model):
active = models.BooleanField(default=True)
name = models.CharField(max_length=40, unique=True)
acronym = models.CharField(max_length=3, unique=True)
class Alarm(models.Model):
active = models.BooleanField(default=True)
product = models.ForeignKey(Product) #NEW
name = models.CharField(unique=True, max_length=35)
image_file = models.CharField(max_length=30)
class File(models.Model):
reference = models.CharField(max_length=40)
product = models.ForeignKey(Product, related_name='item_product') #NEW
created = models.DateTimeField(default=datetime.now)
created_by = models.ForeignKey(User)
class FileAlarm(models.Model):
file = models.ForeignKey(File)
created = models.DateTimeField()
created_by = models.ForeignKey(User, related_name="alarm_created_by")
alarm_date = models.DateField(default=datetime.now)
alarm_type = models.ForeignKey(Alarm)
alarm_comment = models.CharField(max_length=80, blank=True, null=True)
Unfortunatly I need to pass an onChange
event to the form element of FileAlarm.alarm_type
(which means the queryset
in __init__
wont work) so I need to populate the choices=
variable of ChoiceField
. 不幸的是,我需要将
onChange
事件传递给FileAlarm.alarm_type
的表单元素(这意味着__init__
的queryset
无法正常工作),因此我需要填充ChoiceField
的choices=
变量。 I'm just wondering how to do that since I only want alarms that are active
and linked to the same product
s as the File
which the FileAlarm
is linked. 我只是想知道该怎么做,因为我只希望警报是
active
并且与链接FileAlarm
的File
链接到同一product
。
class FileAlarmForm(ModelForm):
def __init__(self,file,*args,**kwargs):
super(FileAlarmForm, self).__init__(*args, **kwargs)
self.fields['alarm'].queryset = Alarm.objects.filter(product__id=file.product_id)
alarm_type = ChoiceField(required=True, widget=Select(attrs={'onChange':'updateAlarmImage'})) # << ?!?
It turns out the best way round it was: 事实证明,最好的方法是:
class FileAlarmForm(ModelForm):
def __init__(self,file,*args,**kwargs):
super(FileAlarmForm, self).__init__(*args, **kwargs)
p = Product.objects.get(id=file.product_id)
self.fields['alarm_type'].widget = Select(attrs={'onchange':'updateAlarmImage'})
self.fields['alarm_type'].queryset = Alarm.objects.filter(product=p)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.