[Django]-Django โ€“ CreateView โ€“ Send a custom Error Message if model form is not valid

9๐Ÿ‘

โœ…

You can override the form_invalid(โ€ฆ) method [Django-doc] to add an error message:

from django.contrib import messages

class DocCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): 
    model = Doc
    form_class = DocForm
    template_name = "doc/doc_form.html"
    context_object_name = 'doc'
    success_message = 'Doc successfully created!'
    error_message = 'Error saving the Doc, check fields below.'
    
    def get_success_url(self):
        return reverse('doc-detail', kwargs={'pk': self.object.pk})

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super().form_valid(form)

    def form_invalid(self, form):
        messages.error(self.request, self.error_message)
        return super().form_invalid(form)

2๐Ÿ‘

Try to put message adding in form_submit, something like that:

#views.py

class DocCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): 
    model = Doc
    form_class = DocForm
    template_name = "doc/doc_form.html"
    context_object_name = 'doc'
    success_message = 'Doc successfully created!'
    error_meesage = "Error saving the Doc, check fields below."
    
    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super().form_valid(form)

    def form_submit(self, request):
        if request.method == 'POST':
            form = DocForm(request.POST)
            if form.is_valid():
                form.save()
            else:
                messages.error(self.request, self.error_message)
            return HttpResponseRedirect(reverse('doc-detail'))
    
        return redirect('doc-detail', pk=post.pk)

Leave a comment