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
有没有办法将表单页面上的用户传递给自定义验证器?
答案 0 :(得分:1)
class MyModelForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
self.fields["repo_name"].validator.append(validate_repo_existance)
并从您实例化表单的视图中传递用户:
form = MyModelForm(request.user) # when unbound
form = MyModelForm(request.user, data=request.POST) # when bound
此模式用于您需要传递给Django表单的任何其他数据。
答案 1 :(得分:1)
当前用户存储在请求对象中,可以使用request.user
进行访问。您可以将此用户作为参数传递到表单中。
答案 2 :(得分:1)
这就是我想要的:
views.py
form = MyModelForm(request.user) # when unbound
form = MyModelForm(request.user, data=request.POST) # when bound
validators.py
class RepoValidator(object):
def __init__(self, user):
self.user = user
def __call__(self, value):
#self.user and value are accessible from here
forms.py
class MyModelForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
self.fields["repo_name"].validators.append(RepoValidator(user))
class Meta:
model = MyModel