Warnings (or even info messages) instead of only errors in Django

后端 未结 3 909
小蘑菇
小蘑菇 2021-01-02 06:36

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

Also, how about suppressing warnings/errors?

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-02 07:20

    I had a similar requirement in my Django Admin app. I needed to get a confirmation from the user before saving a possibly duplicate entry. I used the error message itself for this as a workaround. In the message, i added a hidden HTML input. On saving a second time, this input appeared in the form data, in which case i went ahead with saving skipping the warning.

    def MyForm(forms.ModelForm):
        def clean(self):
            if (not self.instance.id and # check only new entries
                'warn_possible_duplicate' not in self.data): # on first save this is true
                # check if possible duplicate
                if possible_duplicate:
                    self.add_error('dup_field', format_html(
                        'Similar entry already exists.'
                        ' To add the new entry anyway, please save again.'
                        ''        # so it's returned in form `data` on second save
                    ))
    

    Any possible flaws with this? Any better suggestions?

提交回复
热议问题