【问题标题】:django form validation - compare inserted datadjango 表单验证 - 比较插入的数据
【发布时间】:2015-01-09 18:22:33
【问题描述】:

关于 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()

以防万一,这些都是必需的。

我希望您能理解我想要实现的目标,也许您可​​以通过一些好的技巧或很好的代码示例来支持我。 谢谢你! :)

【问题讨论】:

    标签: python django forms validation


    【解决方案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
    

    【讨论】:

    • 这看起来真不错!但是在 localhost 中运行时,它给了我这样的错误:异常类型:SyntaxError。异常值:无效语法(forms.py,第 20 行),即:if (title != name)。任何想法,这是从哪里来的?会不会来自我的名字 = client.search(title).name?
    • 很抱歉。忘记在if 语句后添加冒号。答案固定。
    • 哎呀,我也没看到。像魅力一样工作,谢谢!
    • 我知道,你已经回答了我的问题,但如果你有时间,我会再问一个。如果第 3 方 db 发回 HTTPError 404,则代码​​不会像我想的那样引发 ValidationError。如何解决这个问题?
    • 然后使用 try/except 语句将调用包装到第 3 方应用程序。请参阅编辑后的答案。
    猜你喜欢
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 2013-06-18
    • 1970-01-01
    相关资源
    最近更新 更多