如何在Django中使用表单验证中的实例数据? [英] How can I use instance data in form validation in Django?
本文介绍了如何在Django中使用表单验证中的实例数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在努力确保某个用户的列表名称是唯一的。这是我的观点:
I am trying to make sure a list name is unique for a certain user. Here is my view:
list = List(user=user)
new_list_form = ListForm(request.POST, instance=list)
if new_list_form.is_valid():
new_list_form.save()
这里是清理标题(列表名称)的验证器:
And here is the validator that cleans the title (the name of the list):
def clean_title(self):
title = self.cleaned_data['title']
if List.objects.get(user=user, title=title):
raise forms.ValidationError("List title must be unique.")
return title
哪些不起作用,因为'ListForm 'object没有属性'user'
如何从clean_title函数访问instance = list给出的用户变量? / p>
How can I access the user variable given by "instance=list" from the clean_title function?
推荐答案
传递给 ModelForm(instance =)
的对象存储在的ModelForm()。实例
。尝试
The object passed to ModelForm(instance=)
is stored in ModelForm().instance
. Try
if List.objects.get(user=self.instance.user, title=title):
这篇关于如何在Django中使用表单验证中的实例数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文