关于Django,python中的表单和验证的问题。
我有一个字段表单,人们可以在其中插入人名。 但需要他们不能输入名称,而第三方网站不支持这些名称。 我的forms.py:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('title', )
def clean_title(self):
cd = self.cleaned_data
# fields is the line, which checks from a 3rd party db ,
# if the name inserted is supported.
# cleaned_data in the parentheses should be the name, inserted by the user.
fields = client.search(cleaned_data).name
# If the client returns the same name as the user has inserted,
# the post must be valid.
# If the user inserts name, which is not in the 3rd party db,
# the client sends an error as a response and the post can't be accepted.
if (self.cleaned_data.get('title') != fields)
raise ValidationError(
"This name is not supported"
)
return self.cleaned_data
我知道,这段代码很乱,因为我已经尝试了很多不同的方法。
我添加了views.py
def add_model(request):
if request.method == "POST":
form = MyModelForm(request.POST)
if form.is_valid():
# commit=False means the form doesn't save at this time.
# commit defaults to True which means it normally saves.
model_instance = form.save(commit=False)
model_instance.timestamp = timezone.now()
model_instance.save()
return HttpResponseRedirect('/polls/thanks')
else:
form = MyModelForm()
return render(request, "polls/polls.html", {'form': form})
和models.py
class MyModel(models.Model):
title = models.CharField(max_length=25, unique=True, error_messages={'unique':"See nimi on juba lisatud."})
timestamp = models.DateTimeField()
以防万一,这些都是必需的。
我希望,您理解,我想要实现的目标,也许您可以通过一些好的提示或代码的优秀示例来支持我。 谢谢! :)
答案 0 :(得分:1)
clean_
方法中的字段值可用self.cleaned_data['field_name']
:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('title', )
def clean_title(self):
title = self.cleaned_data['title']
try:
name = client.search(title).name
except HTTPError:
raise ValidationError("Can't validate the name. Try again later")
if title != name:
raise ValidationError("This name is not supported")
return title