我尝试使用objectl链接到当前基础对象(从模型中排除其他对象)来创建表单:
forms.py
class RoomTypeForm(ModelForm):
class Meta:
model = RoomType
fields = {'Name', 'Rooms', 'Beds', 'Facilities', 'Capacity'}
exclude = ('Building',)
def __init__(self, *args, **kwargs):
self.building_id = kwargs.pop('building_id')
self.fields['Capacity'].queryset = Capacity.objects.filter(
Building=self.building_id
)
views.py
def building_details(request, hotel_id, building_id):
capacity_form = CapacityForm
roomtype_form = RoomTypeForm
args = {}
args.update(csrf(request))
args['building'] = Building.objects.get(id=building_id)
args['capacity'] = Capacity.objects.filter(Building=building_id)
args['roomtypes'] = RoomType.objects.filter(Building=building_id)
args['capform'] = capacity_form
args['rtform'] = roomtype_form(building_id=building_id)
return render_to_response('building.html', args)
但我有错误:
'RoomTypeForm'对象没有属性'fields'
排队:
self.fields ['Capacity']。queryset = Capacity.objects.filter(建筑物= self.building_id)
怎么可能让所有这些都能奏效?请帮忙。
答案 0 :(得分:1)
您需要拨打super()
__init__
课程
def __init__(self, *args, **kwargs):
self.building_id = kwargs.pop('building_id')
super(RoomTypeForm, self).__init__(*args, **kwargs)
self.fields['Capacity'].queryset = Capacity.objects.filter(Building=self.building_id)
或者如果您使用的是python3,您可以这样做:
super().__init__(*args, **kwargs)
另一方面,标准做法是在fields
中指定列表或元组。你指定了一个集合。