Django advanced usage form specifies field validation data

created at 07-17-2021 views: 15

At work, you will encounter that the data filled in the form needs to be verified separately. This can be solved by using Django's Form or ModelForm

from django import forms
from django.forms import fields
from django.forms import ValidationError

class ObjectsCreateForm(forms.Form):
    name = fields.CharField(max_length=300)

    def clean_name(self):
        # Check if the name is unique
        name = self.cleaned_data.get('name')
        res = Objects.objects.filter(name=name).exists()
        if res:
            raise ValidationError('name already in the database')

        return name

Note: The clean_FIELDNAME() method must have a return value, otherwise the data is empty when using form.cleaned_data.

created at:07-17-2021
edited at: 07-17-2021: