[Django] Display the error message specified by raise ValidationError

It's different from python's normal try and except exception handling, and I'm stuck with exception detection and display of its contents, so I'll keep a record of it.

This time, I would like to write an article about the display of an error message when a unique validation check is caught when checking variations on a form or model.

Brief explanation of the situation

I was developing a simple Blur filter function using OpenCV, and I wanted to ask the user to input the filter size and determine the effect strength (filter size) from that value.

So, I made a form using Form class, but because I used Gaussian filter, I get an error if the input value is even.

From here, I thought about creating a unique variation check for the Form class that "handles an error if the input value is even".

Source code

If you make a mistake, I'm sorry. You don't have to worry too much about models.py.

app/urls.py


app_name = 'app'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
]

models.py


class Image(models.Model):
    img_src = models.ImageField(upload_to=get_upload_to)   

form.py


def is_oddnumber(value): #Function to check if it is odd
    if value % 2 == 0:
        raise ValidationError('Please enter an even number')
class Form(forms.ModelForm):
    class Meta:
        model = Image
        fields = ('img_src')

    filter_size = forms.IntegerField(
        required=True,
        max_value=100,
        min_value=1,
        validators=[is_oddnumber], #Additional is on_Perform validation check with odd number
    )

views.py


class IndexView(generic.TemplateView)
     
    template_name = index.html
    
    def get(self, request, *args, **kwargs):
        form = Form()
        return render(request, self.template_name, {'form': form})

    def post(self, request, *args, **kwargs):
        form = Form(request.POST, request.FILES)
        if form.is_valid():
             return redirect(○)
        return render(request, self.template_name, {'form': form}) #Set the form containing the error message and redisplay

index.html


<form action="{% url 'app:index' %}" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit">
</form>

{% if form.errors %}
<ul>
    {% for error in form.non_field_errors %}
    <li>{{ error }}</li>
    {% endfor %}
</ul>
{% endif %}

It seems that the error message that is the argument of raise ValidationError is stored in form.errors.

Therefore, if a variation error occurs, you can display the error message without screen transition by redisplaying the form containing the error message in form.errors with render.

Recommended Posts

[Django] Display the error message specified by raise ValidationError
Display error message when login fails in Django
[Django] Display message at redirect destination
Django ~ Let's display it in the browser ~
[Django] Error when SlugField is specified in .filter ()
Put the file uploaded by django into MinIO
DJango Memo: From the beginning (Error screen settings)
Display the Django shift table! Supports 20-day closing