admin.ModelAdmin.save_model() 上的 Django 操作

Django action on admin.ModelAdmin.save_model()

我需要收集用户输入表单的信息,然后发送到服务器,我使用的是套接字。

我不是在谈论验证器或管理操作,数据将被保存,但是当它保存时,我需要我上面写的段落中的内容。

我可以发送数据,但如果服务器不活动或无法访问,我想警告用户该操作无法完成。

我该怎么做?

再说一次,必须保存数据。

你懂我吗?

编辑:

这意味着数据应该输入,输入的数据将被保存,如果服务器关闭,用户将收到服务器关闭消息通知。

好的,这就是我所做的:

覆盖 save_model()

from client.exceptions import PrintServerError  # this is my own Exception
super(MyModelAdmin, self).save_model(request, obj, form, change)  # Save object
instruction = Instruction.objects.get(name='print_client_label')  # This model has the server information
    request.POST['instruction'] = instruction
    request.POST['accessory'] = obj
client = Client(server=instruction.printer.server.ip, instruction=instruction.name,
                          username=request.user.id, sn=obj.serial_number.serial_number)  # Client that connects to the server
    if not client.main():  # If an error ocurred, Raise a exception
        raise PrintServerError(client.error)

然后我创建一个中间件,用于处理异常。

将其添加到设置中:

MIDDLEWARE_CLASSES = (
...
'common.middleware.MyMiddleware')

MyMiddleware 代码:

class MyMiddleware(object):
    def process_exception(self, request, exception):
        # Error on app, when trying to connect to the label printer server
        if type(exception) in (error, PrintServerError):
            instruction = request.POST['instruction']
            context = {
                'host': instruction.printer.server.name,
                'ip': instruction.printer.server.ip,
                'template_error': exception.message  # template_error, means template that is used for a label, no Django template
            }
            return render(request, 'myapp/printer_server_error.html', context=context)
        return None

以及模板代码:

{% if not template_error %}
<p>
    El servidor de impresión de etiquetado no responde.<br>
    <br>
    Por favor verifique la configuración de las IP de la maquina conectada a las impresoras y que esta misma, tenga
    conexión a internet.<br>
    <br>
    Información del error:<br>
    <br>
    Nombre del servidor de impresión: <strong>{{ host }}</strong><br>
    Ip del servidor impresión: <strong>{{ ip }}</strong>
    <br>
    <strong>No se ha guardado el cambio.</strong>
</p>
{% else %}
    <p>
    {{ template_error }}
    </p>
{% endif %}

所以,这样可以保存数据,将数据发送到服务器,如果发生错误,用户会被警告。