Validate form and show error to user

I have models MyEvent and MyEventRegistration. Each MyEventRegistration represents the registration to specific MyEvent.

Below is the code I have. I would like to, when the registration form is submitted, check if there is already similar registration - if yes, I would like to show the user message/warning/error “This registration already exists” (or something similar).

I need to check if there already exists MyEventRegistration object with the same name, email and event (the note is not importatant) and if YES, then show the message “This registration already exists”. How can I achieve that ?

Perfect would be if this would be shown within the form as some kind of validation error.

class MyEventRegistration(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
	note = models.TextField(blank=True, null=True)
    event = models.ForeignKey(MyEvent, on_delete=models.CASCADE)

class MyEventRegistrationForm(forms.ModelForm):
    class Meta:
        model = MyEventRegistration
        fields = ['name','email','note']

def register_for_event(request,pk):
	my_event = MyEvent.objects.get(id=pk) # get event for which the registration is to be done
    if request.method == 'POST':
        form = MyEventRegistration(request.POST)
        if form.is_valid():
            r =
            r.event = my_event
            task_new_event_registered( # task for sending 'thank you' email to user
        return redirect('myapp:show_events_page') # show page with all events
        # otherwise show empty form
        form = MyEventRegistrationForm()
        context = {'my_event': my_event, 'form': form}
        return render(request, 'myapp/EventRegistrationPage.html', context) # show page with registration form

In your ModelForm, you can override the clean method to perform whatever detailed validation you wish to perform on an instance of a model.

1 Like