Python 在modelform中显示由pk过滤的已填充组合框
我有这些模型:Python 在modelform中显示由pk过滤的已填充组合框,python,django,Python,Django,我有这些模型: class LocationType(models.Model): Name=models.CharField(max_length=50) Description=models.CharField(max_length=200) class Location(models.Model): Name=models.CharField(max_length=100) ParentCode=models.BigIntegerField() Loca
class LocationType(models.Model):
Name=models.CharField(max_length=50)
Description=models.CharField(max_length=200)
class Location(models.Model):
Name=models.CharField(max_length=100)
ParentCode=models.BigIntegerField()
LocationType=models.ForeignKey(LocationType)
class Visa(models.Model):
Country=models.ForeignKey(Location)
Price=models.CharField(max_length=12)
ActionUser=models.ForeignKey(User,editable=False)
在forms.py
中,我有:
class VisaForm(ModelForm):
class Meta:
model=Visa
我想在Visa表单中显示一个位置组合框(用于Visa模型的国家/地区字段),这些位置由特殊的LocationType
过滤
假设我有一个LocationType
,其值name=Country,pk=1
。在visa\u表中
我想显示位置的列表
s,但不是全部。仅限具有locationType\u id=1的位置
如何填写此组合框并在visa表格中显示?您应该能够使用django ChoiceField。它需要一个argchoices
,您可以将其设置为元组类型(您可以在最后为元组创建一个列表,因为您可能从一个列表开始)。您只需根据name=Country和pk=1筛选对象,然后选择CHOICES
(如果您想命名该变量),然后设置CHOICES=CHOICES
我希望这有帮助
只要将选择字段添加到模型表单
,您就可以从中继承并添加字段。您应该能够使用django选择字段。它需要一个argchoices
,您可以将其设置为元组类型(您可以在最后为元组创建一个列表,因为您可能从一个列表开始)。您只需根据name=Country和pk=1筛选对象,然后选择CHOICES
(如果您想命名该变量),然后设置CHOICES=CHOICES
我希望这有帮助
只要将ChoicesField
添加到ModelForm
中,您就可以从中继承并添加该字段。以下行中的内容:
class VisaForm(ModelForm):
def __init__(self, location_type, *args, **kwargs):
super(VisaForm, self).__init__(*args, **kwargs)
self.fields['Country'] = forms.ModelChoiceField(queryset=Location.objects.filter(LocationType=location_type))
class Meta:
model=Visa
关于以下内容:
class VisaForm(ModelForm):
def __init__(self, location_type, *args, **kwargs):
super(VisaForm, self).__init__(*args, **kwargs)
self.fields['Country'] = forms.ModelChoiceField(queryset=Location.objects.filter(LocationType=location_type))
class Meta:
model=Visa
谢谢大家,我这样做了,它工作了:在init self.fields[“Country”]。queryset=Location.objects.filter(LocationTypeCode\uu id=locationType.id)中,也许这个更适合于这个问题。谢谢大家,我这样做了,它工作了:在init self.fields[“Country”].queryset=Location.objects.filter(LocationTypeCode\uu id=locationType.id)