gpt4 book ai didi

django - 如何在没有 HTML 标记的情况下提取 Django 表单错误消息

转载 作者:行者123 更新时间:2023-12-04 18:59:22 26 4
gpt4 key购买 nike

我需要提取消息和字段。

例如,我有这个 django 表单错误结果

<ul class="errorlist">
<li>__all__
<ul class="errorlist nonfield">
<li>Pointofsale with this Official receipt and Company already exists.</li>
</ul>
</li>
</ul>

从这段代码的输出
def post_sale(request):
sale_form = request["data"]

if sale_form.is_valid():
save_form.save()
else:
print save_form.errors

但我需要实现的是在没有标签的情况下获取消息,所以我可以以纯字符串/文本的形式返回这些消息。
def post_sale(request):
sale_form = request["data"]

if sale_form.is_valid():
save_form.save()
else:
# This is just pseudo code
for field in save_form.errors:
field = str(field["field"})
message = str(field["error_message"])

print "Sale Error Detail"
print field
print message

error_message = { 'field':field,'message':message }
error_messages.append(error_message )

输出将是:
Sale Error Detail
(the field where form error exists)
Pointofsale with this Official receipt and Company already exists.

探索的问题和文档
  • displaying django form error messages instead of just the field name
  • Getting a list of errors in a Django form
  • django form errors. get the error without any html tags
  • How do I display the Django '__all__' form errors in the template?
  • https://docs.djangoproject.com/en/1.10/ref/forms/api/
  • https://docs.djangoproject.com/en/1.10/topics/forms/

  • 谢谢,请告诉我是否有问题或需要澄清,以便我修复它。

    最佳答案

    errors绑定(bind)表单的属性将包含该表单引发的所有错误,作为字典。键是字段或其他特殊值(如 __all__ ),值是一个或多个错误的列表。

    这是一个关于它如何工作的简单示例:

    >>> from django import forms
    >>> class MyForm(forms.Form):
    ... name = forms.CharField()
    ... email = forms.EmailField()
    ...
    >>> f = MyForm() # Note, this is an unbound form
    >>> f.is_valid()
    False
    >>> f.errors # No errors
    {}
    >>> f = MyForm({}) # Now, the form is bound (to an empty dictionary)
    >>> f.is_valid()
    False
    >>> f.errors # dictionary of errors
    {'name': [u'This field is required.'], 'email': [u'This field is required.']}

    在您看来,根据您的需要,您可以返回 form.errors 的值。 ,或将其解析为您需要的任何结构。
    for field, errors in form.errors.items():
    print('Field: {} Errors: {}'.format(field, ','.join(errors))

    对于您提到的特定错误,这是由于覆盖 clean() 而引发的自定义错误。方法 - 这就是为什么它被列在特殊标识符 __all__ 下的原因而不是在特定领域。

    这在 forms reference, under validation 中有所提及:

    Note that any errors raised by your Form.clean() override will not be associated with any field in particular. They go into a special “field” (called __all__), which you can access via the non_field_errors() method if you need to. If you want to attach errors to a specific field in the form, you need to call add_error().

    关于django - 如何在没有 HTML 标记的情况下提取 Django 表单错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41711127/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com