Source

django-confirmation / confirmation / models.py

from django.core.urlresolvers import NoReverseMatch, reverse
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db import models

from confirmation.managers import ConfirmationManager
from confirmation.fields import JSONField
from confirmation import settings


class Confirmation(models.Model):
    """
    Can be used for user activation, but also for
    other purposes where confirmation is required.
    """
    content_type = models.ForeignKey(ContentType, blank=True, null=True)
    object_id = models.PositiveIntegerField(blank=True, null=True)
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    date = models.DateTimeField(auto_now_add=True)
    key = models.CharField(max_length=32)
    token = models.IntegerField(default=1)
    data = JSONField(blank=True, null=True)

    # overriding get and create methods
    objects = ConfirmationManager()
    
    def get_url(self, request, url, *args, **kwargs):
        """
        url parameter is name of named url or relative url path
        """
        try:
            url = reverse(url, args=args, kwargs=kwargs)
        except NoReverseMatch:
            pass

        url = request.build_absolute_uri(url)
        url += '?%(key_name)s=%(key_value)s&%(token_name)s=%(token_value)s' % {
                                                                                'key_name': settings.KEY_NAME, 
                                                                                'key_value': self.key, 
                                                                                'token_name': settings.TOKEN_NAME,
                                                                                'token_value': self.token,
                                                                                }
        return url
    
    class Meta:
        db_table = "confirmation"

    def __unicode__(self):
        return self.key