views:

457

answers:

1

I'm working with Django signals, but they seem to be received twice, even if emitted once. Here's the code I'm working with (it's a simple wrapper to use Uploadify with Django)...

# Signal-emitting code... emits whenever a file upload is received
# ----------------------------------------------------------------
upload_recieved = django.dispatch.Signal(providing_args=['data'])

def upload(request, *args, **kwargs):
    if request.method == 'POST':
        if request.FILES:
            print 'sending signal'
            upload_recieved.send(sender='uploadify', data=request.FILES['Filedata'])
    return HttpResponse('True')

# Signal-receiving code...
# ----------------------------------------------------------------    
def upload_received_handler(sender, data, **kwargs):
    print 'upload received handler'

print 'connecting signal'
upload_recieved.connect(upload_received_handler)

(I just noticed my signal is spelled wrong)

I'm sure you noticed the print statements in there. On the console, this is what it's showing:

(server starts)
connecting signal

...

sending signal
upload received handler
upload received handler     # << == where is this 2nd one coming from?
127.0.0.1 - - [25/Sep/2009 07:28:22] "POST /uploadify/upload/ HTTP/1.1" 200 -

(also odd is why does Django report the page POST after the signals are fired?)

+5  A: 

This has happened to me before and it was due to the module where you are connecting the signal being imported twice. To make sure the signal isn't connected twice you can set the dispatch_uid:

upload_recieved.connect(upload_received_handler, dispatch_uid="some.unique.string.id")

UPDATE It is actually documented here: http://code.djangoproject.com/wiki/Signals#Helppost%5Fsaveseemstobeemittedtwiceforeachsave

Ricky
Very helpful! Thank you.
T. Stone