Mercurial > public > sg101
comparison downloads/receivers.py @ 922:1a832625c047
Downloads app refactor.
For Django 1.7.7 upgrade.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Tue, 07 Apr 2015 20:20:42 -0500 |
parents | downloads/signals.py@929d0e637a37 |
children |
comparison
equal
deleted
inserted
replaced
921:6d08b1476a52 | 922:1a832625c047 |
---|---|
1 """Signal handlers for the downloads application. | |
2 | |
3 We use signals to compute the denormalized category counts whenever a download | |
4 is saved. | |
5 | |
6 """ | |
7 from django.db.models.signals import post_save | |
8 from django.db.models.signals import post_delete | |
9 | |
10 from downloads.models import Category, Download, PendingDownload | |
11 | |
12 | |
13 def on_download_save(sender, **kwargs): | |
14 """This function updates the count field for all categories. | |
15 It is called whenever a download is saved via a signal. | |
16 """ | |
17 if kwargs['created']: | |
18 # we only have to update the parent category | |
19 download = kwargs['instance'] | |
20 cat = download.category | |
21 cat.count = Download.public_objects.filter(category=cat).count() | |
22 cat.save() | |
23 else: | |
24 # update all categories just to be safe (an existing download could | |
25 # have been moved from one category to another | |
26 cats = Category.objects.all() | |
27 for cat in cats: | |
28 cat.count = Download.public_objects.filter(category=cat).count() | |
29 cat.save() | |
30 | |
31 | |
32 def on_download_delete(sender, **kwargs): | |
33 """This function updates the count field for the download's parent | |
34 category. It is called when a download is deleted via a signal. | |
35 | |
36 We now delete the uploaded file when the download is deleted. | |
37 """ | |
38 # update the parent category | |
39 download = kwargs['instance'] | |
40 cat = download.category | |
41 cat.count = Download.public_objects.filter(category=cat).count() | |
42 cat.save() | |
43 | |
44 # delete the actual file | |
45 if download.file: | |
46 download.file.delete(save=False) | |
47 | |
48 | |
49 def on_pending_download_delete(sender, **kwargs): | |
50 """Delete the uploaded file if it exists.""" | |
51 | |
52 download = kwargs['instance'] | |
53 # delete the actual file | |
54 if download.file: | |
55 download.file.delete(save=False) | |
56 | |
57 | |
58 post_save.connect(on_download_save, sender=Download, | |
59 dispatch_uid='downloads.receivers') | |
60 post_delete.connect(on_download_delete, sender=Download, | |
61 dispatch_uid='downloads.receivers') | |
62 post_delete.connect(on_pending_download_delete, sender=PendingDownload, | |
63 dispatch_uid='downloads.receivers') |