简体   繁体   中英

Django ValidationError

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?

您必须使用以下命令在模板中打印非字段错误:

{{ form.non_field_errors }}

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

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