Django - 处理完整性错误并显示错误弹出窗口

Django - Dealing With Integrity Error And Showing Error Pop up

我的 model.py 文件如下。我创建了一个共轭主键 date & station.

Models.py

from django.db import models
from django import forms
# Create your models here.
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User



# Create your models here.
class ManHour(models.Model):
    class Meta:
        unique_together = (('date', 'station'),)

    station_choices = (
       ('KHI','Station1'),
       ('ISB', 'Station2'),
       ('LHE','Station3'),
       )

    station = models.CharField(
        max_length=3,
        choices=station_choices,
    )
    date = models.DateField()
    date_time  = models.DateTimeField(auto_now=True)
    imports_airside = models.DecimalField(max_digits= 5, decimal_places= 3, default = 0)
    imports_landside = models.DecimalField(max_digits= 5, decimal_places= 3, default = 0)
    exports = models.DecimalField(max_digits= 5, decimal_places= 3, default = 0)

Form.py

from django import forms
from manhourapp.models import ManHour
from datetime import date

class DateInput(forms.DateInput):
    input_type = 'date'

class InputForm(forms.ModelForm):
    class Meta:
        model = ManHour
        fields = ['date','station', 'imports_airside', 'imports_landside', 'exports']
        widgets = {
            'date':forms.widgets.DateInput(attrs={'type': 'date', 'max':str(date.today())})
        }

Views.py

def form_page(request):
    context = {}

    try:
        man_hour = ManHour.objects.get(pk=request.GET.get("pk"))
    except ManHour.DoesNotExist:
        man_hour = None

    if man_hour:
        context["Total_Imports"] = man_hour.imports_airside + man_hour.imports_landside


    if man_hour:
        context["Total_Hours"] = man_hour.imports_airside + man_hour.imports_landside + man_hour.exports

    if request.method == 'POST':
        properties_Form = InputForm(request.POST, instance=man_hour)
        if properties_Form.is_valid():
            obj = properties_Form.save()
            return redirect("%s?pk=%s" % (reverse('form'), obj.pk))
    else:   
        context['form']= InputForm(instance=man_hour)
        return render(request, "form.html", context)

HTML

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" async></script>
    </head>
    <body>
      

        <form target="upload_frame" action="." method="post" enctype="multipart/form-data" >
            {% csrf_token %}
            {{ form.as_p }}<br>
            <input type="text" name="Total_Imports" value="{{ Total_Imports }}" class="form-control" disabled><br>
            <input type="text" name="Total_Hours" value="{{ Total_Hours }}" class="form-control" disabled><br>
            <input type="submit" name="submit" value="Upload" id="submit">
            <div class="user_panel">
                <a href="/logout">logout</a>
            </div>
        </form>           
    </body>
</html>

我是 Django 的新手,我想了解如何显示一个弹出窗口,告诉用户该记录已存在于该日期和站点。

我需要了解如何添加异常处理并向用户显示弹出窗口?

我尝试使用下面的代码添加异常处理,但它不起作用。

try:
    if request.method == 'POST':
        properties_Form = InputForm(request.POST, instance=man_hour)
        if properties_Form.is_valid():
            obj = properties_Form.save()
            return redirect("%s?pk=%s" % (reverse('form'), obj.pk))
except IntegrityError as e:
    error_message = e.__cause__
    print(error_message)

A Form class 在 Django 中将为您执行验证和清理。它会 不会 引发错误但会自己捕获错误,因此使用 try-except 没有多大意义,因为表单本身已捕获错误。

相反,您只需要 return 一个响应,以防 .is_valid() returns False。此外,当您呈现表单时,表单本身会呈现错误以将其显示给用户,因此您应该再次呈现相同的页面:

if request.method == 'POST':
    properties_Form = InputForm(request.POST, instance=man_hour)
    if properties_Form.is_valid():
        obj = properties_Form.save()
        return redirect("%s?pk=%s" % (reverse('form'), obj.pk))
    context['form'] = properties_Form
    return render(request, "form.html", context) # form was not valid so returning a response here

如果要自定义生成的错误消息,可以通过在表单的 Meta class 上设置 error_messages 属性来实现(参见 Considerations regarding model’s error_messages [Django docs]):

from django.core.exceptions import NON_FIELD_ERRORS


class InputForm(forms.ModelForm):
    class Meta:
        model = ManHour
        fields = ['date','station', 'imports_airside', 'imports_landside', 'exports']
        widgets = {
            'date':forms.widgets.DateInput(attrs={'type': 'date', 'max':str(date.today())})
        }
        <b>error_messages = {
            NON_FIELD_ERRORS: {
                'unique_together': "%(model_name)s's %(field_labels)s are not unique.",
            }
        }</b>