如果我尝试在django表单中添加一个新对象,我如何将初始值传递给这个新表单?
我知道如何在表单init上设置初始值,但我不知道如何在新表单中进行表单
任何帮助?enter code here
Model A
X = CharField()
Y = ForeignKey(ModelB)
Model B
Z = CharField()
设置X后保存模型的值。 我能够在ModelA表单中添加新对象Y,这将打开一种新形式的ModelB。如何将X的值传递给刚刚打开的新表单? 我需要X来对Z进行查询,我无法找到解决方案
编辑:
class PrecoPorEpocaForm(forms.ModelForm):
class Meta:
model = Preco_por_epoca
fields = ('epoca',)
def __init__(self, *args, **kwargs):
super(PrecoPorEpocaForm, self).__init__(*args, **kwargs)
#if kwargs['initial']['epoca_hotel']:
# print kwargs['initial']['epoca_hotel']
# self.fields['epoca'].queryset = Epoca.objects.filter(hotel=s)
#print "TTTTTTTTTTTTTTT"
class TabelaPrecoForm(forms.ModelForm):
class Meta:
model = TabelaPrecos
fields = ('client', 'year','hotel', 'seasonprice', 'teste')
def __init__(self, *args, **kwargs):
super(TabelaPrecoForm, self).__init__(*args, **kwargs)
if self.instance.hotel != None:
self.fields['seasonprice'].queryset = Preco_por_epoca.objects.filter(epoca__hotel = self.instance.hotel)
答案 0 :(得分:0)
如果我正确地想要做什么,你需要扭转关系:
class ModelA(models.Model):
X = CharField()
class Model B(models.Model):
Z = CharField()
model_A_ref = ForeignKey(ModelA)
然后在你的admin.py
中做class ModelBAdmin(admin.ModelAdmin):
list_filter=('model_A_ref',)
admin.site.register(ModelB, ModelBAdmin)