Python - Django - 传递参数以形成干净的方法

时间:2017-03-05 19:52:36

标签: python django django-forms django-validation

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

我的代码如下:

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__

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

感谢。

2 个答案:

答案 0 :(得分:2)

您的__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)

答案 1 :(得分:0)

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

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