[英]Python - Django - Pass Argument To Form Clean Method
我试图使用__init__
参数将变量传递给ModelForm清理方法但到目前为止没有成功 - 我查看了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__
。
有谁知道这个问题的根本原因是什么?
谢谢。
你的__init__
方法应该接受*args
和**kwargs
,你应该在调用超类' __init__
方法而不是self
和property_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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.