I have a form which the user can input and I want to test for validation. The user will input a field called Project Name and I want to check if this value already exists in the database. If it does, then raise a warning. Here is my code:
views.py
if form.is_valid():
team_profile = get_object_or_None(Team, Team_ID=profile.team_id)
return render(request,'teams/my_team.html', {'team_profile': team_profile})
else:
return render(request,"teams/team_form.html", {'form':CreateTeamForm()})
models.py
def validate_id_exists(value):
incident = Team.objects.filter(Project_name=value)
if incident: # check if any object exists
raise ValidationError('This already exists not exist.')
class Team(models.Model):
Project_name = models.CharField(max_length=250, validators=[validate_id_exists])
So currently, if the user inputs an already existing project_name it will cause the form to be invalid. However, I do not know, how to show the error message on the screen. Currently, if I submit with an already existing project_name it will just return to the original form which makes sense according to what I wrote. However, I want to display the error message while staying on the form page.
Any ideas?