-1

My question is how do I get an object inside of a function?

class PurchaseOrder(models.Model):
    product = models.CharField(max_length=256)
    vendor = models.CharField(max_length=256)

def send_email_on_new_order(instance, created, raw, **kwargs):
    if not created or raw:
        return

    email=EmailMessage('NEW Purchase Order System', 'message', to=['dason30@gmail.com'])
    email.send()
signals.post_save.connect(send_email_on_new_order, sender= PurchaseOrder, dispatch_uid = 'send_email_on_new_order')

So, for the above program I have it automatically send an email to the user whenever a new primay key is generated. However, how can I make it so the title of the email gives the product inside PurchaseOrder

Mdjon26
  • 2,145
  • 4
  • 19
  • 29

1 Answers1

1

Do you mean this?

def send_email_on_new_order(instance, created, raw, **kwargs):
    if not created or raw:
        return

    product = instance.product

    email=EmailMessage('NEW Purchase Order System {0}'.format(product), 'message', to=['dason30@gmail.com'])
    email.send()

EDIT: Just to clarify - instance.product can safely be an argument for format() method directly. I've intentionally made it more verbose. And of course we could use + instead of format but again this is the way of verbosively indicating that we are inserting data into the string.

ElmoVanKielmo
  • 10,907
  • 2
  • 32
  • 46
  • I'm sorry. Your logic makes sense, but I come from C++ so I'm still having struggles with the syntax. Could you give an example of the .format(product) thing with my code? – Mdjon26 Jul 24 '13 at 21:01
  • 1
    @Mdjon26, the more important is `product = instance.product` - you get instance fields straightforward as you declared them in a `model`. And `str.format()` substitutes the occurencies of `{n}` inside the `str` with it's arguments. And in my answer you have a part of your code with additional line. Do you want anything else? – ElmoVanKielmo Jul 24 '13 at 21:07