Reputation: 1759
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?
Upvotes: 0
Views: 1129
Reputation: 1559
You have to return the invalid form:
//views.py
form = CreateTeamForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
team_profile = get_object_or_None(Team, Team_ID=profile.team_id)
else:
print form.errors
return render(request,"teams/team_form.html", {'form': form})
forms.py
def validate_project_name(value):
incident = Team.objects.filter(Project_name=value)
if incident: # check if any object exists
raise ValidationError('This already exists not exist.')
return value
Upvotes: 1
Reputation: 1079
You have to print your non field errors in your template using:
{{ form.non_field_errors }}
Upvotes: 2