警告(甚至是信息消息),而不是Django中的错误 [英] Warnings (or even info messages) instead of only errors in Django

查看:111
本文介绍了警告(甚至是信息消息),而不是Django中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



还有,如何抑制警告/错误?

解决方案

老问题,但我认为它仍然是相关的。



这真的取决于你您可以接受表单中的部分有效数据(不要在需要警告的字段上提示ValidationError)。




  • 然后,使用 contrib.messages 框架(或类似的),您可能会在下一页上显示一个警告框(无论是相同的表单页面还是重定向到家庭或任何其他页面)

  • 或者,您可能需要确认而不是警告。您可以在创建时动态添加或更改字段,所以为什么不添加隐藏的我接受风险复选框,只有当您的表单提出警告时才需要?


    1. 用户加载表单。复选框是隐藏的HTML输入设置为false。

    2. 用户填写带有警告的数据的表单。

    3. 用户检查框然后重新提交表单。

    4. 服务器正确处理数据并忽略警告。




第二个选项具有不需要Cookie的优点,它还增加了交互性(您的用户可能不想因为警告而继续进行)。



在您的代码中,您需要做的只有这样: / p>

 #views.py 
...
如果form.is_valid():
#继续
else:
form.fields [my_checkbox]。widget = widgets.CheckboxInput
#重新显示窗体
...


#forms.py
...
def clean_myfield(self):
#清理
如果(myfield_warning == True)而不是(my_checkbox == True )
raise ValidationError(blabla)
else:
return myfield

在您看来,您可以检查相应的错误form.errors如果需要。


Does the concept of severity exist in Django's form validation or is it only errors?

Also, how about suppressing warnings/errors?

解决方案

Old question, but I think it is still relevant.

It really depends on what you consider to be a warning.

  • You may accept partially valid data in your form (not raise ValidationError on fields upon which you want warnings). Then, using the contrib.messages framework (or similar), you may display a warning box on the next page (be it the same form page, or a redirection to home or any other page)
  • Alternatively, you might want confirmation instead of a warning. You may add or alter fields dynamically upon creation, so why not add hidden "I accept the risks" checkboxes that are required only if your form raises that warning?

    1. User loads form. Checkbox is an hidden HTML input set to false.
    2. User fills form with data that raises warning. Form is displayed again, but now the checkbox is visible.
    3. User checks box then resubmits their form.
    4. The server handles the data correctly and ignores the warning.

The second option has the advantage of not requiring cookies, and it also adds interactivity (your user might not want to proceed because of the warning...).

In your code, all you would have to do is this:

#views.py
...
if form.is_valid():
    # proceed
else:
    form.fields["my_checkbox"].widget = widgets.CheckboxInput
    # re-display form
...


#forms.py
...
def clean_myfield(self):
    # do your cleaning
    if (myfield_warning==True) and not (my_checkbox==True):
        raise ValidationError("blabla")
    else:
        return myfield

In your view, you may check for appropriate errors in form.errors if needed.

这篇关于警告(甚至是信息消息),而不是Django中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆