【问题标题】:Want to exclude some data from ModelForm想从 ModelForm 中排除一些数据
【发布时间】:2016-04-20 11:30:23
【问题描述】:

我尝试使用仅链接到当前基础对象的 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”对象没有“字段”属性

排队:

self.fields['容量'].queryset = 容量.objects.filter(Building=self.building_id)

如何才能使所有这些工作?请帮忙。

【问题讨论】:

    标签: python django forms modelform


    【解决方案1】:

    你需要调用__init__中的super()

    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 中指定列表或元组是标准做法。你指定了一个集合。

    【讨论】:

    • 谢谢,但它不起作用:__init__() 得到了一个意外的关键字参数“building_id”
    • 将 building_id 移到 super 调用上方
    猜你喜欢
    • 2022-06-30
    • 2020-07-25
    • 2018-11-08
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 2019-05-12
    相关资源
    最近更新 更多