Python - Django - 将参数传递给 Form Clean 方法

Python - Django - Pass Argument To Form Clean Method

我正在尝试使用 __init__ 参数将变量传递给 ModelForm clean 方法,但到目前为止没有成功 - 我查看了 Whosebug 上的各种帖子,但 none 似乎有所帮助。

我的代码如下:

forms.py

class property_booking_form(forms.ModelForm):
    check_in_date = forms.DateField(widget=SelectDateWidget)
    check_out_date = forms.DateField(widget=SelectDateWidget)

    class Meta:
        model = Properties_bookings
        fields = ['check_in_date', 'check_out_date']

    def __init__(self, property_id):
        self.property_id = property_id
        super(property_booking_form, self).__init__(self, property_id)

    def clean(self):
        check_in_date = self.cleaned_data.get('check_in_date')
        check_out_date = self.cleaned_data.get('check_out_date')
        property_min_nights = Properties.objects.get(id=self.property_id).property_minimum_nights
        ...

views.py

def view(request):
    ...
    if request.method == 'POST':
        booking_form = property_booking_form(request.POST, property_id=property_id)
        if booking_form.is_valid():
            ...
    else:
        booking_form = property_booking_form(property_id=property_id)
    return render(...)

这会引发以下错误: 'property_booking_form' 对象没有属性 'get'

根据错误描述,这似乎与小部件有关:

异常位置:

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py in value_from_datadict, line 1058

表单在没有覆盖 __init__.

的情况下工作正常

有谁知道这个问题的根本原因是什么?

谢谢。

你的 __init__ 方法应该接受 *args**kwargs,你应该在调用超类的 __init__ 方法时传递这些,而不是 selfproperty_id.

def __init__(self, property_id, *args, **kwargs):
    self.property_id = property_id
    super(property_booking_form, self).__init__(*args, **kwargs)

您还需要更改在视图中实例化表单的方式,因为 property_id 是第一个参数。例如:

if request.method == 'POST':
    booking_form = property_booking_form(property_id=property_id, data=request.POST)

或者,您可以从签名中删除 property_id,然后从 kwargs 中弹出。在这种情况下,不需要更改视图。

def __init__(self, *args, **kwargs):
    self.property_id = kwargs.pop('property_id')
    super(property_booking_form, self).__init__(*args, **kwargs)

已通过如下修改__init__解决了这个问题:

def __init__(self, *args, **kwargs):
        self.property_id = kwargs.pop('property_id', None)
        super(property_booking_form, self).__init__(*args, **kwargs)