Django - CreateView - 如果模型表单无效,则发送自定义错误消息

问题描述 投票:0回答:2

我有一些基于类的视图,我使用 Django 消息框架 如果表单 POST

is_valid
,则发送 success_message。

如果表单 POST 无效,我还想发送自定义

error_message

如何配置

success_message
非常明显,只需使用 SuccessMessageMixin 和 添加“success_message”变量。我尝试过同样的方法 error_message,但我的所有尝试都没有显示 表单页面上的错误闪现消息 - 我的尝试在下面的
else:
块中被注释掉。

向 CBV 发送错误消息似乎是一种非常常见的情况,但我在 Django 文档或其他在线地方找不到任何示例。

有谁知道我怎样才能完成这个任务?

澄清一下 - 我不是在谈论添加 ValidationErrors 是为特定领域创建的。我有 ValidationErrors 字段工作正常。这 指的是出现在顶部的自定义闪现消息 页。

#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()
            return HttpResponseRedirect(reverse('doc-detail'))
        else:
            # messages.error(self.request, error_message)
            # messages.add_message(self.request, messages.ERROR, error_message)
            # form = DocForm()
    
        return redirect('doc-detail', pk=post.pk)

#base.html

      {% if messages %}
          {% for message in messages %}
              <div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}">
             {{ message }}<button type="button" class="close" data-dismiss="alert" aria-label="Close">
             <span aria-hidden="true">&times;</span></button></div>
          {% endfor %}
      {% endif %}

      {% block content %}
      {% endblock content %}
python django django-forms django-views
2个回答
10
投票

您可以重写

form_invalid(…)
方法[Django-doc] 添加错误消息:

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
投票

尝试将消息添加到

form_submit
,类似这样的:

#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)
© www.soinside.com 2019 - 2024. All rights reserved.