简体   繁体   中英

Django: Check if user input does not exist in db and throw ValidationError

I have an IntegerField in my form where a user can input an id . Before the form is submitted I want to check if that id actually exists and if it doesn't I want to throw the user a Validation Error if it doesn't. I've tried the following. Is there an easier way to do this?

forms.py

class IncidentSearchForm(forms.Form):
    id = forms.IntegerField(label="ID",required=False)

    def search(self):
        id = self.cleaned_data.get('id')
        try:
            incident_id = Incident.object.filter(pk=id).exists()
        except Incident.DoesNotExist:
            raise forms.ValidationError('This does not exist.')

    query = Incident.objects.all()

    if id is not None:
        query = query.filter(id=self.cleaned_data.get('id'))

    return(query)

you could do something like this inside the form:

def clean_id(self):
    """
    Cleaning id field
    """
    id = self.cleaned_data.get('id', None)
    if id:
        try:
            incident = Incident.objects.get(pk=id)
        except Incident.DoesNotExist():
            raise forms.ValidationError('This does not exist.')
    return id

According to the documentation :

The clean_() method is called on a form subclass – where is replaced with the name of the form field attribute. This method does any cleaning that is specific to that particular attribute, unrelated to the type of field that it is. This method is not passed any parameters. You will need to look up the value of the field in self.cleaned_data and remember that it will be a Python object at this point, not the original string submitted in the form (it will be in cleaned_data because the general field clean() method, above, has already cleaned the data once).

Since you need a custom validator(as you mentioned in comments), you can create a validate_id_exists validator for your id field.

validate_id_exists validator checks if an Incident object exists with the given id . If it does not exists, it raises a ValidationError .

from django.core.exceptions import ValidationError

def validate_id_exists(value):
    incident = Incident.objects.filter(id=value)
    if not incident: # check if any object exists
        raise ValidationError('This does not exist.') 

Then you can specify this validator in your form as validators argument to id field.

class IncidentSearchForm(forms.Form):
    id = forms.IntegerField(label="ID", required=False, validators=[validate_id_exists]) # specify your 'id' validator here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM