0

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?

2 Answers 2

2

You have to print your non field errors in your template using:

{{ form.non_field_errors }}
Sign up to request clarification or add additional context in comments.

2 Comments

How? Do i have to something to my views?
Yes add the template tag mentioned in the answer to your template with the form.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.