Как вернуть сообщение об ошибке для поля PROTECT на DJANGO - PullRequest
0 голосов
/ 03 августа 2020

Я не знаю, как вернуть простое сообщение об ошибке на django, например, мне нужно вернуть ЗАЩИТУ Ошибка при удалении этого ОБЪЕКТА:

МОЙ ПРОСМОТР:

    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)

СПАСИБО!

1 Ответ

0 голосов
/ 03 августа 2020

Ваше представление должно быть примерно таким:

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, вы можете передать сообщение об ошибке в контекстный словарь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...