Two scoops of Django建议做一个自定义验证的形式如下:如何将当前用户传递给自定义表单验证器?
class MyModel(models.Model):
body = models.TextField()
repo_name = models.CharField(max_length=50)
def validate_repo_existance(value):
# Validate repo existance.
# This needs the Github account which is bound
# to the user account though.
class MyModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
self.fields["repo_name"].validators.append(validate_repo_existance)
class Meta:
model = MyModel
有没有办法通过,是表单页面自定义验证的用户?
很酷,但我怎么能'__init__'方法''用户''validate_repo_existance'?看来你只能传递一个没有参数的函数对象。 – Bentley4
对于简单的字段验证'clean_fieldname()'方法就足够了,如果你正在基于多个字段中的值进行验证,使用'clean()'方法。如果你需要使用验证器(顺便说一句,你可能意思是'self.validators.fields [“repo_name”]。append(validate_repo_existance)',你跳过了'validators'部分),你可以使用一个在构造函数中获取用户的类。看看Django如何做到这一点:https://github.com/django/django/blob/master/django/forms/fields.py#L212 – waverider
谢谢你为我提供了重要的线索。另外,感谢您的纠正,我忘了在我的问题中编写'validators'属性(但它是在我的真实代码中)。 – Bentley4