将参数传递给 Django ModelForm clean 方法
我试图将参数传递给 ModelForm 的 clean 方法,以便我可以对某些数据执行一些额外的验证。
在我的views.py 文件中,我有:
page_data = page_form.cleaned_data(foo="bar")
在我的clean_url 方法中,我有:
def clean_url(self, **kwargs):
url = self.cleaned_data['url']
if kwargs['foo'] == url:
query = FlatPage.objects.filter(url=url)
if query.exists():
raise forms.ValidationError(("This url is already being used by the '%s' page.") % (query[0].title))
return url
我不断收到foo
的KeyError。我不确定我在哪里犯了错误,因为我之前已经传递过 kwarg 变量,但从未传递给干净的方法。
I am trying to pass an argument to the clean method of my ModelForm so that I can perform some extra validation on some data.
In my views.py file, I have:
page_data = page_form.cleaned_data(foo="bar")
In my clean_url method, I have:
def clean_url(self, **kwargs):
url = self.cleaned_data['url']
if kwargs['foo'] == url:
query = FlatPage.objects.filter(url=url)
if query.exists():
raise forms.ValidationError(("This url is already being used by the '%s' page.") % (query[0].title))
return url
I keep getting a KeyError for foo
. I'm not sure where I'm making a mistake here, as I've passed kwarg variables before, but never to a clean method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关键在于通过 ModelForm 的 init 方法传递参数:
然后可以通过调用 self.url 在 clean 方法中引用该变量
The key lies in passing the paramaters through the ModelForm's init method:
This variable can then be referenced in the clean method by calling self.url
使用基于类的视图时,您可以使用
get_form_kwargs
将变量从视图传递到您的表单,然后传递给您的 clean 方法:在您的视图中:
在您的表单中:
然后引用 self. url 在您的
clean()
方法中。When using Class Based Views, you can use
get_form_kwargs
to pass the variable from the view to your form and then to you clean method:In your view:
In your form:
And then reference
self.url
in yourclean()
method.