subscribe.forms: 27 total statements, 100.0% covered

Generated: Thu 2013-02-28 14:58 SGT

Source file: /Users/martin/Repos/django-subscribe/subscribe/forms.py

Stats: 24 executed, 0 missed, 3 excluded, 20 ignored

  1. """Forms for the ``subscribe`` app."""
  2. from django import forms
  3. from django.contrib.contenttypes.models import ContentType
  4. from .models import Subscription
  5. class SubscriptionCreateForm(forms.Form):
  6. def __init__(self, user, content_object, *args, **kwargs):
  7. self.user = user
  8. self.content_object = content_object
  9. self.ctype = ContentType.objects.get_for_model(self.content_object)
  10. super(SubscriptionCreateForm, self).__init__(*args, **kwargs)
  11. def _get_method_kwargs(self):
  12. """
  13. Helper method. Returns kwargs needed to filter the correct object.
  14. Can also be used to create the correct object.
  15. """
  16. method_kwargs = {
  17. 'user': self.user,
  18. 'content_type': self.ctype,
  19. 'object_id': self.content_object.pk,
  20. }
  21. return method_kwargs
  22. def save(self, *args, **kwargs):
  23. """Adds a subscription for the given user to the given object."""
  24. method_kwargs = self._get_method_kwargs()
  25. try:
  26. subscription = Subscription.objects.get(**method_kwargs)
  27. except Subscription.DoesNotExist:
  28. subscription = Subscription.objects.create(**method_kwargs)
  29. return subscription
  30. class SubscriptionDeleteForm(SubscriptionCreateForm):
  31. def save(self, *args, **kwargs):
  32. """Removes a subscription for the given user from the given object."""
  33. method_kwargs = self._get_method_kwargs()
  34. try:
  35. subscription = Subscription.objects.get(**method_kwargs)
  36. except Subscription.DoesNotExist:
  37. return
  38. subscription.delete()