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)
- [Django]-Django makemigrations No changes detected in app
- [Django]-Fabric: unable to get environment variables within virtualenv
- [Django]-Creating a User Registration Page using MongoEngine
- [Django]-Implementing a SOA in Django using celery
Source:stackexchange.com