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

后端 未结 3 906
小蘑菇
小蘑菇 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:15

    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.

    0 讨论(0)
  • 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.'
                        '<input type="hidden" id="warn-possible-duplicate"' # inject hidden input with error msg itself
                        'name="warn_possible_duplicate" value="0"/>'        # so it's returned in form `data` on second save
                    ))
    

    Any possible flaws with this? Any better suggestions?

    0 讨论(0)
  • 2021-01-02 07:26

    Django forms can only raise ValidationErrors (see here). One way to get around this is to use the new messaging system. There are 5 levels of messages defined, with the ability to define additional custom message levels.

    As for suppressing errors/warnings, you can always simply ignore form.errors in your template. Also take a look at the clean methods in the forms module - you should be able to suppress some warnings there.

    0 讨论(0)
提交回复
热议问题