Reputation: 1006
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)
Upvotes: 0
Views: 4046
Reputation: 47846
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
Upvotes: 2
Reputation: 1297
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).
Upvotes: 1