1

Ok so Im saving a CSV document to a Machine object. I want to notifiy the user that the Machine does not exist if it does not exist and exit the save. I first read the CSV file to see what machine the document is for by reading a serial number row.

In my signals:

@receiver(post_save, sender=CSVDocument)
def read_file(sender,instance, signal, created, **kwargs):
    ...
    machine = Machine.objects.get(serial_number=sn)
    if not machine:
        customNotificationMessage in admin tempalte

I do not want to raise an exception at this stage, rather tell the user there is no such machine, so first create the machine.

Currently if I take out the try block to lookupt the machine it raises the exception:

Machine matching query does not exist. Lookup parameters were {'serial_number': 'NEC03610154'}

I would actually just want this execption as part of the messages after the file is saved.

Harry
  • 13,091
  • 29
  • 107
  • 167

1 Answers1

0

Just catch that exception and print the message out:

@receiver(post_save, sender=CSVDocument)
def read_file(sender,instance, signal, created, **kwargs):
    ...
    try:
        machine = Machine.objects.get(serial_number=sn)
    exception Machine.DoesNotExist:
        machine = None
        error_message = 'Machine matching query does not exist'
    if not machine:
        customNotificationMessage in admin template
        print error_message

Another option is to use filter() instead of get():

machine = Machine.objects.filter(serial_number=sn)

You will get an empty queryset if there is no match.

Hope it helps.

Hieu Nguyen
  • 8,563
  • 2
  • 36
  • 43