【问题标题】:Django action on admin.ModelAdmin.save_model()对 admin.ModelAdmin.save_model() 的 Django 操作
【发布时间】:2015-10-08 03:55:45
【问题描述】:

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

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

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

我该怎么做?

同样,必须保存数据。

你明白我的意思吗?

编辑:

表示需要输入数据,输入的数据将被保存,如果服务器宕机,用户将收到服务器宕机消息。

【问题讨论】:

  • “你明白我的意思吗?”很抱歉,不!

标签: python django django-admin


【解决方案1】:

好的,这就是我所做的:

覆盖 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')

我的中间件代码:

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 %}

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

【讨论】:

    猜你喜欢
    • 2018-06-25
    • 2010-12-30
    • 2021-02-13
    • 2013-09-09
    • 1970-01-01
    • 2011-07-13
    • 2010-10-15
    • 2021-04-23
    • 2012-09-29
    相关资源
    最近更新 更多