好的,这就是我所做的:
覆盖 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 %}
因此,这可以保存数据,将数据发送到服务器,如果发生错误,将警告用户。