【问题标题】:How do I return Message error for PROTECT Field on DJANGO如何在 DJANGO 上返回 PROTECT 字段的消息错误
【发布时间】:2020-08-03 17:43:04
【问题描述】:

我不会为 django 上的错误返回简单的消息,例如,我需要在删除此 OBJECT 时返回 PROTECT Error:

我的看法:

    def delete_notafiscal(request, notafiscal_id):
        notafiscal = NotaFiscal.objects.get(id=notafiscal_id)
        context={'object':notafiscal,'forms':''}
        try:
            if request.method =="POST":
                notafiscal.delete()
                return HttpResponseRedirect(reverse("controles:notasfiscais"))
            
        except ProtectedError as e:
            print("erro",e)
        
        return render(request,'controles/notafiscal_confirm_delete.html',context)

我的模板

    <form method="post">{% csrf_token %}
        <p>Você irá deletar "{{ object }}"?</p>
        <input type="submit" value="Confirm">
    </form>

模型

    class NotaFiscal(models.Model):
        nome = models.CharField(max_length=50)
        documento = models.FileField(upload_to='uploads/notafiscal/')
      
    class Item(models.Model):
        id_item = models.AutoField(primary_key=True)
        id_notafiscal = models.ForeignKey(NotaFiscal, on_delete=models.PROTECT, blank=True, null = True)

谢谢!

【问题讨论】:

    标签: python django frameworks


    【解决方案1】:

    你的视图应该是这样的:

    def delete_notafiscal(request, notafiscal_id):
        try:
            notafiscal = NotaFiscal.objects.get(id=notafiscal_id)
            context={'object':notafiscal,'forms':'', 'error': ''}
            if request.method =="POST":
                notafiscal.delete()
                return HttpResponseRedirect(reverse("controles:notasfiscais"))
        
        # NotaFiscal will throw a DoesNotExist exception if the result does not exist
        except NotaFiscal.DoesNotExist:
            context['error'] = 'NotaFiscal does not exist'
            
        except ProtectedError as e:
            context['error'] ='An error occured'
        
        return render(request,'controles/notafiscal_confirm_delete.html',context)
    

    虽然我没有看到 ProtectedError 的定义位置,但由于您没有使用 django 表单,您可以将错误消息传递给上下文字典。

    【讨论】:

    • 谢谢!成功了!
    • 不客气。如果它确实回答了您的问题,您可以将其标记为答案
    猜你喜欢
    • 2014-12-20
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 2012-09-25
    • 2019-09-04
    • 1970-01-01
    相关资源
    最近更新 更多