<commit_before># Licensed under the Apache License, Version 2.0 (the 'License'); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at http://www.apache.org/licenses/LICENSE-2.0
# Copyright 2015 Marc Sibson

from datetime import datetime
import time

try:
    import simplejson as json
except ImportError:
    import json

from celery.beat import Scheduler, ScheduleEntry
from celery.utils.log import get_logger
from celery.signals import beat_init
from celery.utils.timeutils import humanize_seconds
from celery.app import app_or_default

from redis.client import StrictRedis

from decoder import RedBeatJSONEncoder, RedBeatJSONDecoder

def add_defaults(app=None):
    app = app_or_default(app)

    app.add_defaults({
        'REDBEAT_REDIS_URL': app.conf['BROKER_URL'],
        'REDBEAT_KEY_PREFIX': 'redbeat:',
        'REDBEAT_SCHEDULE_KEY': app.conf.get('REDBEAT_KEY_PREFIX', 'redbeat:') + ':schedule',
        'REDBEAT_STATICS_KEY': app.conf.get('REDBEAT_KEY_PREFIX', 'redbeat:') + ':statics',
        'REDBEAT_LOCK_KEY': app.conf.get('REDBEAT_KEY_PREFIX', 'redbeat:') + ':lock',
        'REDBEAT_LOCK_TIMEOUT': app.conf.CELERYBEAT_MAX_LOOP_INTERVAL * 5,
    })

def redis(app=None):
    app = app_or_default(app)

    if not hasattr(app, 'redbeat_redis') or app.redbeat_redis is None:
        app.redbeat_redis = StrictRedis.from_url(app.conf.REDBEAT_REDIS_URL)

    return app.redbeat_redis

ADD_ENTRY_ERROR = """\

Couldn't add entry %r to redis schedule: %r. Contents: %r
"""

logger = get_logger(__name__)

def to_timestamp(dt):
    return time.mktime(dt.timetuple())

class RedBeatSchedulerEntry(ScheduleEntry):
    _meta = None

    def __init__(self, name=None, task=None, schedule=None, args=None, kwargs=None, enabled=True, **clsargs):
        super(RedBeatSchedulerEntry, self).__init__(name, task, schedule=schedule,
                                                    args=args, kwargs=kwargs, **clsargs)
        self.enabled = enabled

    @staticmethod
    def load_definition(key, app=None, definition=None):
        if definition is None:
            definition = redis(app).hget(key, 'definition')

        if definition is None:
            raise KeyError(key)

        definition = json.loads(definition, cls=RedBeatJSONDecoder)
        if not definition:
            raise KeyError(key)

        return definition

    @staticmethod
    def load_meta(key, app=None, meta=None):
        if meta is None:
            meta = redis(app).hget(key, 'meta')

        if not meta:
            return {'last_run_at': datetime.min}

        return json.loads(meta, cls=RedBeatJSONDecoder)

    @staticmethod
    def from_key(key, app=None):
        with redis(app).pipeline() as pipe:
            pipe.hget(key, 'definition')
            pipe.hget(key, 'meta')
            definition, meta = pipe.execute()

        definition = RedBeatSchedulerEntry.load_definition(key, definition=definition or '{}')
        meta = RedBeatSchedulerEntry.load_meta(key, meta=meta or '{}')
        definition.update(meta)

        return RedBeatSchedulerEntry(app=app, **definition)

    @property
    def due_at(self):
        delta = self.schedule.remaining_estimate(self.last_run_at)
        return self.last_run_at + delta

    @property
    def key(self):
        return app_or_default(self.app).conf['REDBEAT_KEY_PREFIX'] + self.name

    @property
    def score(self):
        return to_timestamp(self.due_at)

    def save(self):
        definition = {
            'name': self.name,
            'task': self.task,
            'args': self.args,
            'kwargs': self.kwargs,
            'options': self.options,
            'schedule': self.schedule,
            'enabled': self.enabled,
        }
        with redis(self.app).pipeline() as pipe:
            pipe.hset(self.key, 'definition', json.dumps(definition, cls=RedBeatJSONEncoder))
            pipe.zadd(self.app.conf.REDBEAT_SCHEDULE_KEY, self.score, self.key)
            pipe.execute()

        return self

    def delete(self):
        with redis(self.app).pipeline() as pipe:
            pipe.zrem(self.app.conf.REDBEAT_SCHEDULE_KEY, self.key)
            pipe.delete(self.key)
            pipe.execute()

    def _next_instance(self, last_run_at=None, only_update_last_run_at=False):
        entry = super(RedBeatSchedulerEntry, self)._next_instance(last_run_at=last_run_at)

        if only_update_last_run_at:
            entry.total_run_count = self.total_run_count

        meta = {
            'last_run_at': entry.last_run_at,
            'total_run_count': entry.total_run_count,
        }
        with redis(self.app).pipeline() as pipe:
            pipe.hset(self.key, 'meta', json.dumps(meta, cls=RedBeatJSONEncoder))
            pipe.zadd(self.app.conf.REDBEAT_SCHEDULE_KEY, entry.score, entry.key)
            pipe.execute()

        return entry
    __next__ = next = _next_instance

    def reschedule(self, last_run_at=None):
        self.last_run_at = last_run_at or self._default_now()
        meta = {
            'last_run_at': self.last_run_at,
        }
        with redis(self.app).pipeline() as pipe:
            pipe.hset(self.key, 'meta', json.dumps(meta, cls=RedBeatJSONEncoder))
            pipe.zadd(self.app.conf.REDBEAT_SCHEDULE_KEY, self.score, self.key)
            pipe.execute()

    def is_due(self):
        if not self.enabled:
            return False, 5.0  # 5 second delay for re-enable.

        return super(RedBeatSchedulerEntry, self).is_due()

class RedBeatScheduler(Scheduler):
    # how often should we sync in schedule information
    # from the backend redis database
    Entry = RedBeatSchedulerEntry

    lock = None

    def __init__(self, app, **kwargs):
        add_defaults(app)
        self.lock_key = kwargs.pop('lock_key', app.conf.REDBEAT_LOCK_KEY)
        self.lock_timeout = kwargs.pop('lock_timeout', app.conf.REDBEAT_LOCK_TIMEOUT)
        super(RedBeatScheduler, self).__init__(app, **kwargs)

    def setup_schedule(self):
        # cleanup old static entries
        client = redis(self.app)
        previous = client.smembers(self.app.conf.REDBEAT_STATICS_KEY)
        current = set(self.app.conf.CELERYBEAT_SCHEDULE.keys())
        removed = previous - current
        for name in removed:
            RedBeatSchedulerEntry(name).delete()

        # setup statics
        self.install_default_entries(self.app.conf.CELERYBEAT_SCHEDULE)
        if not self.app.conf.CELERYBEAT_SCHEDULE:
            return

        self.update_from_dict(self.app.conf.CELERYBEAT_SCHEDULE)

        # track static entries
        client.sadd(self.app.conf.REDBEAT_STATICS_KEY, *self.app.conf.CELERYBEAT_SCHEDULE.keys())

    def update_from_dict(self, dict_):
        for name, entry in dict_.items():
            try:
                entry = self._maybe_entry(name, entry)
            except Exception as exc:
                logger.error(ADD_ENTRY_ERROR, name, exc, entry)
                continue

            entry.save()  # store into redis
            logger.debug(unicode(entry))

    def reserve(self, entry):
        new_entry = next(entry)
        return new_entry

    @property
    def schedule(self):
        logger.debug('Selecting tasks')

        max_due_at = to_timestamp(self.app.now())
        client = redis(self.app)

        with client.pipeline() as pipe:
            pipe.zrangebyscore(self.app.conf.REDBEAT_SCHEDULE_KEY, 0, max_due_at)

            # peek into the next tick to accuratly calculate sleep between ticks
            pipe.zrangebyscore(self.app.conf.REDBEAT_SCHEDULE_KEY,
                               '({}'.format(max_due_at),
                               max_due_at + self.max_interval,
                               start=0, num=1)
            due_tasks, maybe_due = pipe.execute()

        logger.info('Loading %d tasks', len(due_tasks) + len(maybe_due))
        d = {}
        for key in due_tasks + maybe_due:
            try:
                entry = self.Entry.from_key(key, app=self.app)
            except KeyError:
                logger.warning('failed to load %s, removing', key)
                client.zrem(self.app.conf.REDBEAT_SCHEDULE_KEY, key)
                continue

            d[entry.name] = entry

        logger.debug('Processing tasks')

        return d

    def tick(self, **kwargs):
        if self.lock:
            logger.debug('beat: Extending lock...')
            redis(self.app).pexpire(self.lock_key, int(self.lock_timeout * 1000))
        return super(RedBeatScheduler, self).tick(**kwargs)

    def close(self):
        if self.lock:
            logger.debug('beat: Releasing Lock')
            self.lock.release()
            self.lock = None
        super(RedBeatScheduler, self).close()

    @property
    def info(self):
        info = ['       . redis -> {}'.format(self.app.conf.REDBEAT_REDIS_URL)]
        if self.lock_key:
            info.append('       . lock -> `{}` {} ({}s)'.format(self.lock_key, humanize_seconds(self.lock_timeout), self.lock_timeout))
        return '\n'.join(info)

@beat_init.connect
def acquire_distributed_beat_lock(sender=None, **kwargs):
    scheduler = sender.scheduler
    if not scheduler.lock_key:
        return

    lock = redis(scheduler.app).lock(scheduler.lock_key, timeout=scheduler.lock_timeout, sleep=scheduler.max_interval)
    logger.debug('beat: Acquiring lock...')
    lock.acquire()
    scheduler.lock = lock
<commit_msg>honour the configured keyprefix<commit_after># Licensed under the Apache License, Version 2.0 (the 'License'); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at http://www.apache.org/licenses/LICENSE-2.0
# Copyright 2015 Marc Sibson

from datetime import datetime
import time

try:
    import simplejson as json
except ImportError:
    import json

from celery.beat import Scheduler, ScheduleEntry
from celery.utils.log import get_logger
from celery.signals import beat_init
from celery.utils.timeutils import humanize_seconds
from celery.app import app_or_default

from redis.client import StrictRedis

from decoder import RedBeatJSONEncoder, RedBeatJSONDecoder

def add_defaults(app=None):
    app = app_or_default(app)

    app.add_defaults({
        'REDBEAT_REDIS_URL': app.conf['BROKER_URL'],
        'REDBEAT_KEY_PREFIX': app.conf.get('REDBEAT_KEY_PREFIX', 'redbeat:'),
        'REDBEAT_SCHEDULE_KEY': app.conf.get('REDBEAT_KEY_PREFIX', 'redbeat:') + ':schedule',
        'REDBEAT_STATICS_KEY': app.conf.get('REDBEAT_KEY_PREFIX', 'redbeat:') + ':statics',
        'REDBEAT_LOCK_KEY': app.conf.get('REDBEAT_KEY_PREFIX', 'redbeat:') + ':lock',
        'REDBEAT_LOCK_TIMEOUT': app.conf.CELERYBEAT_MAX_LOOP_INTERVAL * 5,
    })

def redis(app=None):
    app = app_or_default(app)

    if not hasattr(app, 'redbeat_redis') or app.redbeat_redis is None:
        app.redbeat_redis = StrictRedis.from_url(app.conf.REDBEAT_REDIS_URL)

    return app.redbeat_redis

ADD_ENTRY_ERROR = """\

Couldn't add entry %r to redis schedule: %r. Contents: %r
"""

logger = get_logger(__name__)

def to_timestamp(dt):
    return time.mktime(dt.timetuple())

class RedBeatSchedulerEntry(ScheduleEntry):
    _meta = None

    def __init__(self, name=None, task=None, schedule=None, args=None, kwargs=None, enabled=True, **clsargs):
        super(RedBeatSchedulerEntry, self).__init__(name, task, schedule=schedule,
                                                    args=args, kwargs=kwargs, **clsargs)
        self.enabled = enabled

    @staticmethod
    def load_definition(key, app=None, definition=None):
        if definition is None:
            definition = redis(app).hget(key, 'definition')

        if definition is None:
            raise KeyError(key)

        definition = json.loads(definition, cls=RedBeatJSONDecoder)
        if not definition:
            raise KeyError(key)

        return definition

    @staticmethod
    def load_meta(key, app=None, meta=None):
        if meta is None:
            meta = redis(app).hget(key, 'meta')

        if not meta:
            return {'last_run_at': datetime.min}

        return json.loads(meta, cls=RedBeatJSONDecoder)

    @staticmethod
    def from_key(key, app=None):
        with redis(app).pipeline() as pipe:
            pipe.hget(key, 'definition')
            pipe.hget(key, 'meta')
            definition, meta = pipe.execute()

        definition = RedBeatSchedulerEntry.load_definition(key, definition=definition or '{}')
        meta = RedBeatSchedulerEntry.load_meta(key, meta=meta or '{}')
        definition.update(meta)

        return RedBeatSchedulerEntry(app=app, **definition)

    @property
    def due_at(self):
        delta = self.schedule.remaining_estimate(self.last_run_at)
        return self.last_run_at + delta

    @property
    def key(self):
        return app_or_default(self.app).conf['REDBEAT_KEY_PREFIX'] + self.name

    @property
    def score(self):
        return to_timestamp(self.due_at)

    def save(self):
        definition = {
            'name': self.name,
            'task': self.task,
            'args': self.args,
            'kwargs': self.kwargs,
            'options': self.options,
            'schedule': self.schedule,
            'enabled': self.enabled,
        }
        with redis(self.app).pipeline() as pipe:
            pipe.hset(self.key, 'definition', json.dumps(definition, cls=RedBeatJSONEncoder))
            pipe.zadd(self.app.conf.REDBEAT_SCHEDULE_KEY, self.score, self.key)
            pipe.execute()

        return self

    def delete(self):
        with redis(self.app).pipeline() as pipe:
            pipe.zrem(self.app.conf.REDBEAT_SCHEDULE_KEY, self.key)
            pipe.delete(self.key)
            pipe.execute()

    def _next_instance(self, last_run_at=None, only_update_last_run_at=False):
        entry = super(RedBeatSchedulerEntry, self)._next_instance(last_run_at=last_run_at)

        if only_update_last_run_at:
            entry.total_run_count = self.total_run_count

        meta = {
            'last_run_at': entry.last_run_at,
            'total_run_count': entry.total_run_count,
        }
        with redis(self.app).pipeline() as pipe:
            pipe.hset(self.key, 'meta', json.dumps(meta, cls=RedBeatJSONEncoder))
            pipe.zadd(self.app.conf.REDBEAT_SCHEDULE_KEY, entry.score, entry.key)
            pipe.execute()

        return entry
    __next__ = next = _next_instance

    def reschedule(self, last_run_at=None):
        self.last_run_at = last_run_at or self._default_now()
        meta = {
            'last_run_at': self.last_run_at,
        }
        with redis(self.app).pipeline() as pipe:
            pipe.hset(self.key, 'meta', json.dumps(meta, cls=RedBeatJSONEncoder))
            pipe.zadd(self.app.conf.REDBEAT_SCHEDULE_KEY, self.score, self.key)
            pipe.execute()

    def is_due(self):
        if not self.enabled:
            return False, 5.0  # 5 second delay for re-enable.

        return super(RedBeatSchedulerEntry, self).is_due()

class RedBeatScheduler(Scheduler):
    # how often should we sync in schedule information
    # from the backend redis database
    Entry = RedBeatSchedulerEntry

    lock = None

    def __init__(self, app, **kwargs):
        add_defaults(app)
        self.lock_key = kwargs.pop('lock_key', app.conf.REDBEAT_LOCK_KEY)
        self.lock_timeout = kwargs.pop('lock_timeout', app.conf.REDBEAT_LOCK_TIMEOUT)
        super(RedBeatScheduler, self).__init__(app, **kwargs)

    def setup_schedule(self):
        # cleanup old static entries
        client = redis(self.app)
        previous = client.smembers(self.app.conf.REDBEAT_STATICS_KEY)
        current = set(self.app.conf.CELERYBEAT_SCHEDULE.keys())
        removed = previous - current
        for name in removed:
            RedBeatSchedulerEntry(name).delete()

        # setup statics
        self.install_default_entries(self.app.conf.CELERYBEAT_SCHEDULE)
        if not self.app.conf.CELERYBEAT_SCHEDULE:
            return

        self.update_from_dict(self.app.conf.CELERYBEAT_SCHEDULE)

        # track static entries
        client.sadd(self.app.conf.REDBEAT_STATICS_KEY, *self.app.conf.CELERYBEAT_SCHEDULE.keys())

    def update_from_dict(self, dict_):
        for name, entry in dict_.items():
            try:
                entry = self._maybe_entry(name, entry)
            except Exception as exc:
                logger.error(ADD_ENTRY_ERROR, name, exc, entry)
                continue

            entry.save()  # store into redis
            logger.debug(unicode(entry))

    def reserve(self, entry):
        new_entry = next(entry)
        return new_entry

    @property
    def schedule(self):
        logger.debug('Selecting tasks')

        max_due_at = to_timestamp(self.app.now())
        client = redis(self.app)

        with client.pipeline() as pipe:
            pipe.zrangebyscore(self.app.conf.REDBEAT_SCHEDULE_KEY, 0, max_due_at)

            # peek into the next tick to accuratly calculate sleep between ticks
            pipe.zrangebyscore(self.app.conf.REDBEAT_SCHEDULE_KEY,
                               '({}'.format(max_due_at),
                               max_due_at + self.max_interval,
                               start=0, num=1)
            due_tasks, maybe_due = pipe.execute()

        logger.info('Loading %d tasks', len(due_tasks) + len(maybe_due))
        d = {}
        for key in due_tasks + maybe_due:
            try:
                entry = self.Entry.from_key(key, app=self.app)
            except KeyError:
                logger.warning('failed to load %s, removing', key)
                client.zrem(self.app.conf.REDBEAT_SCHEDULE_KEY, key)
                continue

            d[entry.name] = entry

        logger.debug('Processing tasks')

        return d

    def tick(self, **kwargs):
        if self.lock:
            logger.debug('beat: Extending lock...')
            redis(self.app).pexpire(self.lock_key, int(self.lock_timeout * 1000))
        return super(RedBeatScheduler, self).tick(**kwargs)

    def close(self):
        if self.lock:
            logger.debug('beat: Releasing Lock')
            self.lock.release()
            self.lock = None
        super(RedBeatScheduler, self).close()

    @property
    def info(self):
        info = ['       . redis -> {}'.format(self.app.conf.REDBEAT_REDIS_URL)]
        if self.lock_key:
            info.append('       . lock -> `{}` {} ({}s)'.format(
                self.lock_key, humanize_seconds(self.lock_timeout), self.lock_timeout))
        return '\n'.join(info)

@beat_init.connect
def acquire_distributed_beat_lock(sender=None, **kwargs):
    scheduler = sender.scheduler
    if not scheduler.lock_key:
        return

    logger.debug('beat: Acquiring lock...')

    lock = redis(scheduler.app).lock(
            scheduler.lock_key, timeout=scheduler.lock_timeout, sleep=scheduler.max_interval)
    lock.acquire()
    scheduler.lock = lock
<|endoftext|>


<commit_before>from registrasion.controllers.product import ProductController
from registrasion.models import commerce
from registrasion.models import inventory

from django import forms
from django.core.exceptions import ValidationError
from django.db.models import Q

class ApplyCreditNoteForm(forms.Form):

    def __init__(self, user, *a, **k):
        ''' User: The user whose invoices should be made available as
        choices. '''
        self.user = user
        super(ApplyCreditNoteForm, self).__init__(*a, **k)

        self.fields["invoice"].choices = self._unpaid_invoices

    def _unpaid_invoices(self):
        invoices = commerce.Invoice.objects.filter(
            status=commerce.Invoice.STATUS_UNPAID,
        ).select_related("user")

        invoices_annotated = [invoice.__dict__ for invoice in invoices]
        users = dict((inv.user.id, inv.user) for inv in invoices)
        for invoice in invoices_annotated:
            invoice.update({
                "user_id": users[invoice["user_id"]].id,
                "user_email": users[invoice["user_id"]].email,
            })

        key = lambda inv: (0 - (inv["user_id"] == self.user.id), inv["id"])
        invoices_annotated.sort(key=key)

        template = "Invoice %(id)d - user: %(user_email)s (%(user_id)d) -  $%(value)d"
        return [
            (invoice["id"], template % invoice)
            for invoice in invoices_annotated
        ]

    invoice = forms.ChoiceField(
        required=True,
    )
    verify = forms.BooleanField(
        required=True,
        help_text="Have you verified that this is the correct invoice?",
    )

class CancellationFeeForm(forms.Form):

    percentage = forms.DecimalField(
        required=True,
        min_value=0,
        max_value=100,
    )

class ManualCreditNoteRefundForm(forms.ModelForm):

    class Meta:
        model = commerce.ManualCreditNoteRefund
        fields = ["reference"]

class ManualPaymentForm(forms.ModelForm):

    class Meta:
        model = commerce.ManualPayment
        fields = ["reference", "amount"]

# Products forms -- none of these have any fields: they are to be subclassed
# and the fields added as needs be. ProductsForm (the function) is responsible
# for the subclassing.

def ProductsForm(category, products):
    ''' Produces an appropriate _ProductsForm subclass for the given render
    type. '''

    # Each Category.RENDER_TYPE value has a subclass here.
    cat = inventory.Category
    RENDER_TYPES = {
        cat.RENDER_TYPE_QUANTITY: _QuantityBoxProductsForm,
        cat.RENDER_TYPE_RADIO: _RadioButtonProductsForm,
        cat.RENDER_TYPE_ITEM_QUANTITY: _ItemQuantityProductsForm,
    }

    # Produce a subclass of _ProductsForm which we can alter the base_fields on
    class ProductsForm(RENDER_TYPES[category.render_type]):
        pass

    ProductsForm.set_fields(category, products)

    if category.render_type == inventory.Category.RENDER_TYPE_ITEM_QUANTITY:
        ProductsForm = forms.formset_factory(
            ProductsForm,
            formset=_ItemQuantityProductsFormSet,
        )

    return ProductsForm

class _HasProductsFields(object):

    PRODUCT_PREFIX = "product_"

    ''' Base class for product entry forms. '''
    def __init__(self, *a, **k):
        if "product_quantities" in k:
            initial = self.initial_data(k["product_quantities"])
            k["initial"] = initial
            del k["product_quantities"]
        super(_HasProductsFields, self).__init__(*a, **k)

    @classmethod
    def field_name(cls, product):
        return cls.PRODUCT_PREFIX + ("%d" % product.id)

    @classmethod
    def set_fields(cls, category, products):
        ''' Sets the base_fields on this _ProductsForm to allow selecting
        from the provided products. '''
        pass

    @classmethod
    def initial_data(cls, product_quantites):
        ''' Prepares initial data for an instance of this form.
        product_quantities is a sequence of (product,quantity) tuples '''
        return {}

    def product_quantities(self):
        ''' Yields a sequence of (product, quantity) tuples from the
        cleaned form data. '''
        return iter([])

    def add_product_error(self, product, error):
        ''' Adds an error to the given product's field '''

        ''' if product in field_names:
            field = field_names[product]
        elif isinstance(product, inventory.Product):
            return
        else:
            field = None '''

        self.add_error(self.field_name(product), error)

class _ProductsForm(_HasProductsFields, forms.Form):
    pass

class _QuantityBoxProductsForm(_ProductsForm):
    ''' Products entry form that allows users to enter quantities
    of desired products. '''

    @classmethod
    def set_fields(cls, category, products):
        for product in products:
            if product.description:
                help_text = "$%d each -- %s" % (
                    product.price,
                    product.description,
                )
            else:
                help_text = "$%d each" % product.price

            field = forms.IntegerField(
                label=product.name,
                help_text=help_text,
                min_value=0,
                max_value=500,  # Issue #19. We should figure out real limit.
            )
            cls.base_fields[cls.field_name(product)] = field

    @classmethod
    def initial_data(cls, product_quantities):
        initial = {}
        for product, quantity in product_quantities:
            initial[cls.field_name(product)] = quantity

        return initial

    def product_quantities(self):
        for name, value in self.cleaned_data.items():
            if name.startswith(self.PRODUCT_PREFIX):
                product_id = int(name[len(self.PRODUCT_PREFIX):])
                yield (product_id, value)

class _RadioButtonProductsForm(_ProductsForm):
    ''' Products entry form that allows users to enter quantities
    of desired products. '''

    FIELD = "chosen_product"

    @classmethod
    def set_fields(cls, category, products):
        choices = []
        for product in products:
            choice_text = "%s -- $%d" % (product.name, product.price)
            choices.append((product.id, choice_text))

        if not category.required:
            choices.append((0, "No selection"))

        cls.base_fields[cls.FIELD] = forms.TypedChoiceField(
            label=category.name,
            widget=forms.RadioSelect,
            choices=choices,
            empty_value=0,
            coerce=int,
        )

    @classmethod
    def initial_data(cls, product_quantities):
        initial = {}

        for product, quantity in product_quantities:
            if quantity > 0:
                initial[cls.FIELD] = product.id
                break

        return initial

    def product_quantities(self):
        ours = self.cleaned_data[self.FIELD]
        choices = self.fields[self.FIELD].choices
        for choice_value, choice_display in choices:
            if choice_value == 0:
                continue
            yield (
                choice_value,
                1 if ours == choice_value else 0,
            )

    def add_product_error(self, product, error):
        self.add_error(self.FIELD, error)

class _ItemQuantityProductsForm(_ProductsForm):
    ''' Products entry form that allows users to select a product type, and
     enter a quantity of that product. This version _only_ allows a single
     product type to be purchased. This form is usually used in concert with
     the _ItemQuantityProductsFormSet to allow selection of multiple
     products.'''

    CHOICE_FIELD = "choice"
    QUANTITY_FIELD = "quantity"

    @classmethod
    def set_fields(cls, category, products):
        choices = []

        if not category.required:
            choices.append((0, "---"))

        for product in products:
            choice_text = "%s -- $%d each" % (product.name, product.price)
            choices.append((product.id, choice_text))

        cls.base_fields[cls.CHOICE_FIELD] = forms.TypedChoiceField(
            label=category.name,
            widget=forms.Select,
            choices=choices,
            initial=0,
            empty_value=0,
            coerce=int,
        )

        cls.base_fields[cls.QUANTITY_FIELD] = forms.IntegerField(
            label="Quantity",  # TODO: internationalise
            min_value=0,
            max_value=500,  # Issue #19. We should figure out real limit.
        )

    @classmethod
    def initial_data(cls, product_quantities):
        initial = {}

        for product, quantity in product_quantities:
            if quantity > 0:
                initial[cls.CHOICE_FIELD] = product.id
                initial[cls.QUANTITY_FIELD] = quantity
                break

        return initial

    def product_quantities(self):
        our_choice = self.cleaned_data[self.CHOICE_FIELD]
        our_quantity = self.cleaned_data[self.QUANTITY_FIELD]
        choices = self.fields[self.CHOICE_FIELD].choices
        for choice_value, choice_display in choices:
            if choice_value == 0:
                continue
            yield (
                choice_value,
                our_quantity if our_choice == choice_value else 0,
            )

    def add_product_error(self, product, error):
        if self.CHOICE_FIELD not in self.cleaned_data:
            return

        if product.id == self.cleaned_data[self.CHOICE_FIELD]:
            self.add_error(self.CHOICE_FIELD, error)
            self.add_error(self.QUANTITY_FIELD, error)

class _ItemQuantityProductsFormSet(_HasProductsFields, forms.BaseFormSet):

    @classmethod
    def set_fields(cls, category, products):
        raise ValueError("set_fields must be called on the underlying Form")

    @classmethod
    def initial_data(cls, product_quantities):
        ''' Prepares initial data for an instance of this form.
        product_quantities is a sequence of (product,quantity) tuples '''

        f = [
            {
                _ItemQuantityProductsForm.CHOICE_FIELD: product.id,
                _ItemQuantityProductsForm.QUANTITY_FIELD: quantity,
            }
            for product, quantity in product_quantities
            if quantity > 0
        ]
        return f

    def product_quantities(self):
        ''' Yields a sequence of (product, quantity) tuples from the
        cleaned form data. '''

        products = set()
        # Track everything so that we can yield some zeroes
        all_products = set()

        for form in self:
            if form.empty_permitted and not form.cleaned_data:
                # This is the magical empty form at the end of the list.
                continue

            for product, quantity in form.product_quantities():
                all_products.add(product)
                if quantity == 0:
                    continue
                if product in products:
                    form.add_error(
                        _ItemQuantityProductsForm.CHOICE_FIELD,
                        "You may only choose each product type once.",
                    )
                    form.add_error(
                        _ItemQuantityProductsForm.QUANTITY_FIELD,
                        "You may only choose each product type once.",
                    )
                products.add(product)
                yield product, quantity

        for product in (all_products - products):
            yield product, 0

    def add_product_error(self, product, error):
        for form in self.forms:
            form.add_product_error(product, error)

    @property
    def errors(self):
        _errors = super(_ItemQuantityProductsFormSet, self).errors
        if False not in [not form.errors for form in self.forms]:
            return []
        else:
            return _errors

class VoucherForm(forms.Form):
    voucher = forms.CharField(
        label="Voucher code",
        help_text="If you have a voucher code, enter it here",
        required=False,
    )

def staff_products_form_factory(user):
    ''' Creates a StaffProductsForm that restricts the available products to
    those that are available to a user. '''

    products = inventory.Product.objects.all()
    products = ProductController.available_products(user, products=products)

    product_ids = [product.id for product in products]
    product_set = inventory.Product.objects.filter(id__in=product_ids)

    class StaffProductsForm(forms.Form):
        ''' Form for allowing staff to add an item to a user's cart. '''

        product = forms.ModelChoiceField(
            widget=forms.Select,
            queryset=product_set,
        )

        quantity = forms.IntegerField(
            min_value=0,
        )

    return StaffProductsForm

def staff_products_formset_factory(user):
    ''' Creates a formset of StaffProductsForm for the given user. '''
    form_type = staff_products_form_factory(user)
    return forms.formset_factory(form_type)

class InvoicesWithProductAndStatusForm(forms.Form):
    invoice = forms.ModelMultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
        queryset=commerce.Invoice.objects.all(),
    )

    def __init__(self, *a, **k):
        category = k.pop('category', None) or []
        product = k.pop('product', None) or []
        status = int(k.pop('status', None) or 0)

        category = [int(i) for i in category]
        product = [int(i) for i in product]

        super(InvoicesWithProductAndStatusForm, self).__init__(*a, **k)
        print status

        qs = commerce.Invoice.objects.filter(
            status=status or commerce.Invoice.STATUS_UNPAID,
        ).filter(
            Q(lineitem__product__category__in=category) |
            Q(lineitem__product__in=product)
        )

        # Uniqify
        qs = commerce.Invoice.objects.filter(
            id__in=qs,
        )

        qs = qs.select_related("user__attendee__attendeeprofilebase")
        qs = qs.order_by("id")

        self.fields['invoice'].queryset = qs
        #self.fields['invoice'].initial = [i.id for i in qs] # UNDO THIS LATER

class InvoiceEmailForm(InvoicesWithProductAndStatusForm):

    ACTION_PREVIEW = 1
    ACTION_SEND = 2

    ACTION_CHOICES = (
        (ACTION_PREVIEW, "Preview"),
        (ACTION_SEND, "Send emails"),
    )

    from_email = forms.CharField()
    subject = forms.CharField()
    body = forms.CharField(
        widget=forms.Textarea,
    )
    action = forms.TypedChoiceField(
        widget=forms.RadioSelect,
        coerce=int,
        choices=ACTION_CHOICES,
        initial=ACTION_PREVIEW,
    )
<commit_msg>first attempt at a checkbox form handler. renders properly, does not validate however. basically a copy and paste of the radio selector with a few tweaks.<commit_after>from registrasion.controllers.product import ProductController
from registrasion.models import commerce
from registrasion.models import inventory

from django import forms
from django.core.exceptions import ValidationError
from django.db.models import Q

class ApplyCreditNoteForm(forms.Form):

    def __init__(self, user, *a, **k):
        ''' User: The user whose invoices should be made available as
        choices. '''
        self.user = user
        super(ApplyCreditNoteForm, self).__init__(*a, **k)

        self.fields["invoice"].choices = self._unpaid_invoices

    def _unpaid_invoices(self):
        invoices = commerce.Invoice.objects.filter(
            status=commerce.Invoice.STATUS_UNPAID,
        ).select_related("user")

        invoices_annotated = [invoice.__dict__ for invoice in invoices]
        users = dict((inv.user.id, inv.user) for inv in invoices)
        for invoice in invoices_annotated:
            invoice.update({
                "user_id": users[invoice["user_id"]].id,
                "user_email": users[invoice["user_id"]].email,
            })

        key = lambda inv: (0 - (inv["user_id"] == self.user.id), inv["id"])
        invoices_annotated.sort(key=key)

        template = "Invoice %(id)d - user: %(user_email)s (%(user_id)d) -  $%(value)d"
        return [
            (invoice["id"], template % invoice)
            for invoice in invoices_annotated
        ]

    invoice = forms.ChoiceField(
        required=True,
    )
    verify = forms.BooleanField(
        required=True,
        help_text="Have you verified that this is the correct invoice?",
    )

class CancellationFeeForm(forms.Form):

    percentage = forms.DecimalField(
        required=True,
        min_value=0,
        max_value=100,
    )

class ManualCreditNoteRefundForm(forms.ModelForm):

    class Meta:
        model = commerce.ManualCreditNoteRefund
        fields = ["reference"]

class ManualPaymentForm(forms.ModelForm):

    class Meta:
        model = commerce.ManualPayment
        fields = ["reference", "amount"]

# Products forms -- none of these have any fields: they are to be subclassed
# and the fields added as needs be. ProductsForm (the function) is responsible
# for the subclassing.

def ProductsForm(category, products):
    ''' Produces an appropriate _ProductsForm subclass for the given render
    type. '''

    # Each Category.RENDER_TYPE value has a subclass here.
    cat = inventory.Category
    RENDER_TYPES = {
        cat.RENDER_TYPE_QUANTITY: _QuantityBoxProductsForm,
        cat.RENDER_TYPE_RADIO: _RadioButtonProductsForm,
        cat.RENDER_TYPE_ITEM_QUANTITY: _ItemQuantityProductsForm,
        cat.RENDER_TYPE_CHECKBOX: _CheckboxProductsForm,
    }

    # Produce a subclass of _ProductsForm which we can alter the base_fields on
    class ProductsForm(RENDER_TYPES[category.render_type]):
        pass

    ProductsForm.set_fields(category, products)

    if category.render_type == inventory.Category.RENDER_TYPE_ITEM_QUANTITY:
        ProductsForm = forms.formset_factory(
            ProductsForm,
            formset=_ItemQuantityProductsFormSet,
        )

    return ProductsForm

class _HasProductsFields(object):

    PRODUCT_PREFIX = "product_"

    ''' Base class for product entry forms. '''
    def __init__(self, *a, **k):
        if "product_quantities" in k:
            initial = self.initial_data(k["product_quantities"])
            k["initial"] = initial
            del k["product_quantities"]
        super(_HasProductsFields, self).__init__(*a, **k)

    @classmethod
    def field_name(cls, product):
        return cls.PRODUCT_PREFIX + ("%d" % product.id)

    @classmethod
    def set_fields(cls, category, products):
        ''' Sets the base_fields on this _ProductsForm to allow selecting
        from the provided products. '''
        pass

    @classmethod
    def initial_data(cls, product_quantites):
        ''' Prepares initial data for an instance of this form.
        product_quantities is a sequence of (product,quantity) tuples '''
        return {}

    def product_quantities(self):
        ''' Yields a sequence of (product, quantity) tuples from the
        cleaned form data. '''
        return iter([])

    def add_product_error(self, product, error):
        ''' Adds an error to the given product's field '''

        ''' if product in field_names:
            field = field_names[product]
        elif isinstance(product, inventory.Product):
            return
        else:
            field = None '''

        self.add_error(self.field_name(product), error)

class _ProductsForm(_HasProductsFields, forms.Form):
    pass

class _QuantityBoxProductsForm(_ProductsForm):
    ''' Products entry form that allows users to enter quantities
    of desired products. '''

    @classmethod
    def set_fields(cls, category, products):
        for product in products:
            if product.description:
                help_text = "$%d each -- %s" % (
                    product.price,
                    product.description,
                )
            else:
                help_text = "$%d each" % product.price

            field = forms.IntegerField(
                label=product.name,
                help_text=help_text,
                min_value=0,
                max_value=500,  # Issue #19. We should figure out real limit.
            )
            cls.base_fields[cls.field_name(product)] = field

    @classmethod
    def initial_data(cls, product_quantities):
        initial = {}
        for product, quantity in product_quantities:
            initial[cls.field_name(product)] = quantity

        return initial

    def product_quantities(self):
        for name, value in self.cleaned_data.items():
            if name.startswith(self.PRODUCT_PREFIX):
                product_id = int(name[len(self.PRODUCT_PREFIX):])
                yield (product_id, value)

class _RadioButtonProductsForm(_ProductsForm):
    ''' Products entry form that allows users to enter quantities
    of desired products. '''

    FIELD = "chosen_product"

    @classmethod
    def set_fields(cls, category, products):
        choices = []
        for product in products:
            choice_text = "%s -- $%d" % (product.name, product.price)
            choices.append((product.id, choice_text))

        if not category.required:
            choices.append((0, "No selection"))

        cls.base_fields[cls.FIELD] = forms.TypedChoiceField(
            label=category.name,
            widget=forms.RadioSelect,
            choices=choices,
            empty_value=0,
            coerce=int,
        )

    @classmethod
    def initial_data(cls, product_quantities):
        initial = {}

        for product, quantity in product_quantities:
            if quantity > 0:
                initial[cls.FIELD] = product.id
                break

        return initial

    def product_quantities(self):
        ours = self.cleaned_data[self.FIELD]
        choices = self.fields[self.FIELD].choices
        for choice_value, choice_display in choices:
            if choice_value == 0:
                continue
            yield (
                choice_value,
                1 if ours == choice_value else 0,
            )

    def add_product_error(self, product, error):
        self.add_error(self.FIELD, error)

class _CheckboxProductsForm(_ProductsForm):
    ''' Products entry form that allows users to say yes or no
    to desired products. '''

    FIELD = "chosen_product"

    @classmethod
    def set_fields(cls, category, products):
        choices = []
        for product in products:
            choice_text = "%s -- $%d" % (product.name, product.price)
            choices.append((product.id, choice_text))

        cls.base_fields[cls.FIELD] = forms.TypedMultipleChoiceField(
            label=category.name,
            widget=forms.CheckboxSelectMultiple,
            choices=choices,
            empty_value=False,
            coerce=int,
        )

    @classmethod
    def initial_data(cls, product_quantities):
        initial = {}

        for product, quantity in product_quantities:
            if quantity > 0:
                initial[cls.FIELD] = product.id

        return initial

    def product_quantities(self):

        print 'product_quantities'
        ours = self.cleaned_data[self.FIELD]
        choices = self.fields[self.FIELD].choices

        print('ours', ours)
        print('choices', choices)

        for choice_value in choices:
            print 'choice_value', choice_value
            if choice_value == 0:
                continue
            yield (
                choice_value,
                1 if ours == choice_value else 0,
            )

    def add_product_error(self, product, error):
        self.add_error(self.FIELD, error)

class _ItemQuantityProductsForm(_ProductsForm):
    ''' Products entry form that allows users to select a product type, and
     enter a quantity of that product. This version _only_ allows a single
     product type to be purchased. This form is usually used in concert with
     the _ItemQuantityProductsFormSet to allow selection of multiple
     products.'''

    CHOICE_FIELD = "choice"
    QUANTITY_FIELD = "quantity"

    @classmethod
    def set_fields(cls, category, products):
        choices = []

        if not category.required:
            choices.append((0, "---"))

        for product in products:
            choice_text = "%s -- $%d each" % (product.name, product.price)
            choices.append((product.id, choice_text))

        cls.base_fields[cls.CHOICE_FIELD] = forms.TypedChoiceField(
            label=category.name,
            widget=forms.Select,
            choices=choices,
            initial=0,
            empty_value=0,
            coerce=int,
        )

        cls.base_fields[cls.QUANTITY_FIELD] = forms.IntegerField(
            label="Quantity",  # TODO: internationalise
            min_value=0,
            max_value=500,  # Issue #19. We should figure out real limit.
        )

    @classmethod
    def initial_data(cls, product_quantities):
        initial = {}

        for product, quantity in product_quantities:
            if quantity > 0:
                initial[cls.CHOICE_FIELD] = product.id
                initial[cls.QUANTITY_FIELD] = quantity
                break

        return initial

    def product_quantities(self):
        our_choice = self.cleaned_data[self.CHOICE_FIELD]
        our_quantity = self.cleaned_data[self.QUANTITY_FIELD]
        choices = self.fields[self.CHOICE_FIELD].choices
        for choice_value, choice_display in choices:
            if choice_value == 0:
                continue
            yield (
                choice_value,
                our_quantity if our_choice == choice_value else 0,
            )

    def add_product_error(self, product, error):
        if self.CHOICE_FIELD not in self.cleaned_data:
            return

        if product.id == self.cleaned_data[self.CHOICE_FIELD]:
            self.add_error(self.CHOICE_FIELD, error)
            self.add_error(self.QUANTITY_FIELD, error)

class _ItemQuantityProductsFormSet(_HasProductsFields, forms.BaseFormSet):

    @classmethod
    def set_fields(cls, category, products):
        raise ValueError("set_fields must be called on the underlying Form")

    @classmethod
    def initial_data(cls, product_quantities):
        ''' Prepares initial data for an instance of this form.
        product_quantities is a sequence of (product,quantity) tuples '''

        f = [
            {
                _ItemQuantityProductsForm.CHOICE_FIELD: product.id,
                _ItemQuantityProductsForm.QUANTITY_FIELD: quantity,
            }
            for product, quantity in product_quantities
            if quantity > 0
        ]
        return f

    def product_quantities(self):
        ''' Yields a sequence of (product, quantity) tuples from the
        cleaned form data. '''

        products = set()
        # Track everything so that we can yield some zeroes
        all_products = set()

        for form in self:
            if form.empty_permitted and not form.cleaned_data:
                # This is the magical empty form at the end of the list.
                continue

            for product, quantity in form.product_quantities():
                all_products.add(product)
                if quantity == 0:
                    continue
                if product in products:
                    form.add_error(
                        _ItemQuantityProductsForm.CHOICE_FIELD,
                        "You may only choose each product type once.",
                    )
                    form.add_error(
                        _ItemQuantityProductsForm.QUANTITY_FIELD,
                        "You may only choose each product type once.",
                    )
                products.add(product)
                yield product, quantity

        for product in (all_products - products):
            yield product, 0

    def add_product_error(self, product, error):
        for form in self.forms:
            form.add_product_error(product, error)

    @property
    def errors(self):
        _errors = super(_ItemQuantityProductsFormSet, self).errors
        if False not in [not form.errors for form in self.forms]:
            return []
        else:
            return _errors

class VoucherForm(forms.Form):
    voucher = forms.CharField(
        label="Voucher code",
        help_text="If you have a voucher code, enter it here",
        required=False,
    )

def staff_products_form_factory(user):
    ''' Creates a StaffProductsForm that restricts the available products to
    those that are available to a user. '''

    products = inventory.Product.objects.all()
    products = ProductController.available_products(user, products=products)

    product_ids = [product.id for product in products]
    product_set = inventory.Product.objects.filter(id__in=product_ids)

    class StaffProductsForm(forms.Form):
        ''' Form for allowing staff to add an item to a user's cart. '''

        product = forms.ModelChoiceField(
            widget=forms.Select,
            queryset=product_set,
        )

        quantity = forms.IntegerField(
            min_value=0,
        )

    return StaffProductsForm

def staff_products_formset_factory(user):
    ''' Creates a formset of StaffProductsForm for the given user. '''
    form_type = staff_products_form_factory(user)
    return forms.formset_factory(form_type)

class InvoicesWithProductAndStatusForm(forms.Form):
    invoice = forms.ModelMultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
        queryset=commerce.Invoice.objects.all(),
    )

    def __init__(self, *a, **k):
        category = k.pop('category', None) or []
        product = k.pop('product', None) or []
        status = int(k.pop('status', None) or 0)

        category = [int(i) for i in category]
        product = [int(i) for i in product]

        super(InvoicesWithProductAndStatusForm, self).__init__(*a, **k)
        print status

        qs = commerce.Invoice.objects.filter(
            status=status or commerce.Invoice.STATUS_UNPAID,
        ).filter(
            Q(lineitem__product__category__in=category) |
            Q(lineitem__product__in=product)
        )

        # Uniqify
        qs = commerce.Invoice.objects.filter(
            id__in=qs,
        )

        qs = qs.select_related("user__attendee__attendeeprofilebase")
        qs = qs.order_by("id")

        self.fields['invoice'].queryset = qs
        #self.fields['invoice'].initial = [i.id for i in qs] # UNDO THIS LATER

class InvoiceEmailForm(InvoicesWithProductAndStatusForm):

    ACTION_PREVIEW = 1
    ACTION_SEND = 2

    ACTION_CHOICES = (
        (ACTION_PREVIEW, "Preview"),
        (ACTION_SEND, "Send emails"),
    )

    from_email = forms.CharField()
    subject = forms.CharField()
    body = forms.CharField(
        widget=forms.Textarea,
    )
    action = forms.TypedChoiceField(
        widget=forms.RadioSelect,
        coerce=int,
        choices=ACTION_CHOICES,
        initial=ACTION_PREVIEW,
    )
<|endoftext|>


<commit_before>"""
Unit tests for django-registration.

"""

import datetime

from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.test import TestCase

from registration import forms
from registration.models import RegistrationProfile

class RegistrationFormTests(TestCase):
    """
    Test the default registration forms.

    """
    def test_registration_form(self):
        """
        Test that ``RegistrationForm`` enforces username constraints
        and matching passwords.

        """
        # Create a user so we can verify that duplicate usernames aren't
        # permitted.
        User.objects.create_user('alice', 'alice@example.com', 'secret')

        invalid_data_dicts = [
            # Non-alphanumeric username.
            {
            'data':
            { 'username': 'foo/bar',
              'email': 'foo@example.com',
              'password1': 'foo',
              'password2': 'foo' },
            'error':
            ('username', [u"This value must contain only letters, numbers and underscores."])
            },
            # Already-existing username.
            {
            'data':
            { 'username': 'alice',
              'email': 'alice@example.com',
              'password1': 'secret',
              'password2': 'secret' },
            'error':
            ('username', [u"This username is already taken. Please choose another."])
            },
            # Mismatched passwords.
            {
            'data':
            { 'username': 'foo',
              'email': 'foo@example.com',
              'password1': 'foo',
              'password2': 'bar' },
            'error':
            ('__all__', [u"You must type the same password each time"])
            },
            ]

        for invalid_dict in invalid_data_dicts:
            form = forms.RegistrationForm(data=invalid_dict['data'])
            self.failIf(form.is_valid())
            self.assertEqual(form.errors[invalid_dict['error'][0]], invalid_dict['error'][1])

        form = forms.RegistrationForm(data={ 'username': 'foo',
                                             'email': 'foo@example.com',
                                             'password1': 'foo',
                                             'password2': 'foo' })
        self.failUnless(form.is_valid())

    def test_registration_form_tos(self):
        """
        Test that ``RegistrationFormTermsOfService`` requires
        agreement to the terms of service.

        """
        form = forms.RegistrationFormTermsOfService(data={ 'username': 'foo',
                                                           'email': 'foo@example.com',
                                                           'password1': 'foo',
                                                           'password2': 'foo' })
        self.failIf(form.is_valid())
        self.assertEqual(form.errors['tos'], [u"You must agree to the terms to register"])

        form = forms.RegistrationFormTermsOfService(data={ 'username': 'foo',
                                                           'email': 'foo@example.com',
                                                           'password1': 'foo',
                                                           'password2': 'foo',
                                                           'tos': 'on' })
        self.failUnless(form.is_valid())

    def test_registration_form_unique_email(self):
        """
        Test that ``RegistrationFormUniqueEmail`` validates uniqueness
        of email addresses.

        """
        # Create a user so we can verify that duplicate addresses
        # aren't permitted.
        User.objects.create_user('alice', 'alice@example.com', 'secret')

        form = forms.RegistrationFormUniqueEmail(data={ 'username': 'foo',
                                                        'email': 'alice@example.com',
                                                        'password1': 'foo',
                                                        'password2': 'foo' })
        self.failIf(form.is_valid())
        self.assertEqual(form.errors['email'], [u"This email address is already in use. Please supply a different email address."])

        form = forms.RegistrationFormUniqueEmail(data={ 'username': 'foo',
                                                        'email': 'foo@example.com',
                                                        'password1': 'foo',
                                                        'password2': 'foo' })
        self.failUnless(form.is_valid())

    def test_registration_form_no_free_email(self):
        """
        Test that ``RegistrationFormNoFreeEmail`` disallows
        registration with free email addresses.

        """
        base_data = { 'username': 'foo',
                      'password1': 'foo',
                      'password2': 'foo' }
        for domain in ('aim.com', 'aol.com', 'email.com', 'gmail.com',
                       'googlemail.com', 'hotmail.com', 'hushmail.com',
                       'msn.com', 'mail.ru', 'mailinator.com', 'live.com'):
            invalid_data = base_data.copy()
            invalid_data['email'] = u"foo@%s" % domain
            form = forms.RegistrationFormNoFreeEmail(data=invalid_data)
            self.failIf(form.is_valid())
            self.assertEqual(form.errors['email'], [u"Registration using free email addresses is prohibited. Please supply a different email address."])

        base_data['email'] = 'foo@example.com'
        form = forms.RegistrationFormNoFreeEmail(data=base_data)
        self.failUnless(form.is_valid())

class DefaultRegistrationBackendTests(TestCase):
    """
    Test the default registration backend.

    Running these tests successfull will require two templates to be
    created for the sending of activation emails; details on these
    templates and their contexts may be found in the documentation for
    the default backend. The setting ``ACCOUNT_ACTIVATION_DAYS`` must
    also be specified, and must be an integer.

    """
    def setUp(self):
        """
        Create an instance of the default backend for use in testing.

        """
        from registration.backends.default import DefaultBackend
        self.backend = DefaultBackend()

    def test_registration(self):
        """
        Test the registration process: registration creates a new
        inactive account and a new profile with activation key,
        populates the correct account data and sends an activation
        email.

        """
        new_user = self.backend.register({}, username='bob', email='bob@example.com', password1='secret')
        self.assertEqual(new_user.username, 'bob')
        self.failUnless(new_user.check_password('secret'))
        self.assertEqual(new_user.email, 'bob@example.com')
        self.failIf(new_user.is_active)
        self.assertEqual(RegistrationProfile.objects.count(), 1)
        self.assertEqual(len(mail.outbox), 1)

    def test_activation(self):
        """
        Test the activation process: activating within the permitted
        window sets the account's ``is_active`` field to ``True`` and
        resets the activation key, while failing to activate within
        the permitted window forbids later activation.

        """
        # First, test with a user activating inside the activation
        # window.
        valid_user = self.backend.register({}, username='alice', email='alice@example.com', password1='swordfish')
        valid_profile = RegistrationProfile.objects.get(user=valid_user)
        activated = self.backend.activate({}, valid_profile.activation_key)
        self.assertEqual(activated.username, valid_user.username)
        self.failUnless(activated.is_active)

        # Fetch the profile again to verify its activation key has
        # been reset.
        valid_profile = RegistrationProfile.objects.get(user=valid_user)
        self.assertEqual(valid_profile.activation_key, RegistrationProfile.ACTIVATED)

        # Now test again, but with a user activating outside the
        # activation window.
        expired_user = self.backend.register({}, username='bob', email='bob@example.com', password1='secret')
        expired_user.date_joined = expired_user.date_joined - datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
        expired_user.save()
        expired_profile = RegistrationProfile.objects.get(user=expired_user)
        self.failIf(self.backend.activate({}, expired_profile.activation_key))
        self.failUnless(expired_profile.activation_key_expired())

    def test_allow(self):
        """
        Test that the setting ``REGISTRATION_OPEN`` appropriately
        controls whether registration is permitted.

        """
        old_allowed = getattr(settings, 'REGISTRATION_OPEN', True)
        settings.REGISTRATION_OPEN = True
        self.failUnless(self.backend.registration_allowed({}))
        settings.REGISTRATION_OPEN = False
        self.failIf(self.backend.registration_allowed({}))
        settings.REGISTRATION_OPEN = old_allowed

    def test_form_class(self):
        """
        Test that the default form class returned is
        ``registration.forms.RegistrationForm``.

        """
        self.failUnless(self.backend.get_form_class({}) is forms.RegistrationForm)

    def test_post_registration_redirect(self):
        """
        Test that the default post-registration redirect is the named
        pattern ``registration_complete``.

        """
        self.assertEqual(self.backend.post_registration_redirect({}, User()),
                         'registration_complete')

class BackendRetrievalTests(TestCase):
    """
    Test that utilities for retrieving the active backend work
    properly.

    """
    def test_get_backend(self):
        """
        Set ``REGISTRATION_BACKEND`` temporarily, then verify that
        ``get_backend()`` returns the correct value.

        """
        from registration import get_backend
        from registration.backends.default import DefaultBackend

        # Stash away the original value of the setting so we can
        # restore it again later.
        old_backend = getattr(settings, 'REGISTRATION_BACKEND', None)

        settings.REGISTRATION_BACKEND = 'registration.backends.default.DefaultBackend'
        self.failUnless(isinstance(get_backend(), DefaultBackend))

        settings.REGISTRATION_BACKEND = old_backend

    def test_backend_error(self):
        """
        Test that an invalid or nonexistent value for the
        ``REGISTRATION_BACKEND`` setting raises the correct exception.

        """
        from registration import get_backend

        old_backend = getattr(settings, 'REGISTRATION_BACKEND', None)

        settings.REGISTRATION_BACKEND = None
        self.assertRaises(ImproperlyConfigured, get_backend)

        # Test nonexistent module
        settings.REGISTRATION_BACKEND = 'registration.backends.doesnotexist.NonExistentBackend'
        self.assertRaises(ImproperlyConfigured, get_backend)

        settings.REGISTRATION_BACKEND = old_backend

class RegistrationViewTests(TestCase):
    """
    Test the registration views.

    """
    urls = 'registration.backends.default.urls'

    def setUp(self):
        """
        Set ``REGISTRATION_BACKEND`` to the default backend, and store
        the original value to be restored later.

        """
        self.old_backend = getattr(settings, 'REGISTRATION_BACKEND', None)
        settings.REGISTRATION_BACKEND = 'registration.backends.default.DefaultBackend'

    def tearDown(self):
        """
        Retore the original value of ``REGISTRATION_BACKEND``.

        """
        settings.REGISTRATION_BACKEND = self.old_backend

    def test_registration_view(self):
        """
        Call the ``register`` view and ensure that it properly
        validates data and creates a new user.

        """
        response = self.client.post(reverse('registration_register'),
                                    data={ 'username': 'alice',
                                           'email': 'alice@example.com',
                                           'password1': 'swordfish',
                                           'password2': 'swordfish' })
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], 'http://testserver%s' % reverse('registration_complete'))
        self.assertEqual(len(mail.outbox), 1)

    def test_activation_view(self):
        """
        Call the ``activate`` view and ensure that it properly
        activates users within the valid activation window, but not
        otherwise.

        """
        # First, register an account.
        self.client.post(reverse('registration_register'),
                         data={ 'username': 'alice',
                                'email': 'alice@example.com',
                                'password1': 'swordfish',
                                'password2': 'swordfish' })
        profile = RegistrationProfile.objects.get(user__username='alice')
        response = self.client.get(reverse('registration_activate',
                                           kwargs={ 'activation_key': profile.activation_key }))
        self.assertEqual(response.status_code, 200)
<commit_msg>Test both activation and failed activation.<commit_after>"""
Unit tests for django-registration.

"""

import datetime

from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.test import TestCase

from registration import forms
from registration.models import RegistrationProfile

class RegistrationFormTests(TestCase):
    """
    Test the default registration forms.

    """
    def test_registration_form(self):
        """
        Test that ``RegistrationForm`` enforces username constraints
        and matching passwords.

        """
        # Create a user so we can verify that duplicate usernames aren't
        # permitted.
        User.objects.create_user('alice', 'alice@example.com', 'secret')

        invalid_data_dicts = [
            # Non-alphanumeric username.
            {
            'data':
            { 'username': 'foo/bar',
              'email': 'foo@example.com',
              'password1': 'foo',
              'password2': 'foo' },
            'error':
            ('username', [u"This value must contain only letters, numbers and underscores."])
            },
            # Already-existing username.
            {
            'data':
            { 'username': 'alice',
              'email': 'alice@example.com',
              'password1': 'secret',
              'password2': 'secret' },
            'error':
            ('username', [u"This username is already taken. Please choose another."])
            },
            # Mismatched passwords.
            {
            'data':
            { 'username': 'foo',
              'email': 'foo@example.com',
              'password1': 'foo',
              'password2': 'bar' },
            'error':
            ('__all__', [u"You must type the same password each time"])
            },
            ]

        for invalid_dict in invalid_data_dicts:
            form = forms.RegistrationForm(data=invalid_dict['data'])
            self.failIf(form.is_valid())
            self.assertEqual(form.errors[invalid_dict['error'][0]], invalid_dict['error'][1])

        form = forms.RegistrationForm(data={ 'username': 'foo',
                                             'email': 'foo@example.com',
                                             'password1': 'foo',
                                             'password2': 'foo' })
        self.failUnless(form.is_valid())

    def test_registration_form_tos(self):
        """
        Test that ``RegistrationFormTermsOfService`` requires
        agreement to the terms of service.

        """
        form = forms.RegistrationFormTermsOfService(data={ 'username': 'foo',
                                                           'email': 'foo@example.com',
                                                           'password1': 'foo',
                                                           'password2': 'foo' })
        self.failIf(form.is_valid())
        self.assertEqual(form.errors['tos'], [u"You must agree to the terms to register"])

        form = forms.RegistrationFormTermsOfService(data={ 'username': 'foo',
                                                           'email': 'foo@example.com',
                                                           'password1': 'foo',
                                                           'password2': 'foo',
                                                           'tos': 'on' })
        self.failUnless(form.is_valid())

    def test_registration_form_unique_email(self):
        """
        Test that ``RegistrationFormUniqueEmail`` validates uniqueness
        of email addresses.

        """
        # Create a user so we can verify that duplicate addresses
        # aren't permitted.
        User.objects.create_user('alice', 'alice@example.com', 'secret')

        form = forms.RegistrationFormUniqueEmail(data={ 'username': 'foo',
                                                        'email': 'alice@example.com',
                                                        'password1': 'foo',
                                                        'password2': 'foo' })
        self.failIf(form.is_valid())
        self.assertEqual(form.errors['email'], [u"This email address is already in use. Please supply a different email address."])

        form = forms.RegistrationFormUniqueEmail(data={ 'username': 'foo',
                                                        'email': 'foo@example.com',
                                                        'password1': 'foo',
                                                        'password2': 'foo' })
        self.failUnless(form.is_valid())

    def test_registration_form_no_free_email(self):
        """
        Test that ``RegistrationFormNoFreeEmail`` disallows
        registration with free email addresses.

        """
        base_data = { 'username': 'foo',
                      'password1': 'foo',
                      'password2': 'foo' }
        for domain in ('aim.com', 'aol.com', 'email.com', 'gmail.com',
                       'googlemail.com', 'hotmail.com', 'hushmail.com',
                       'msn.com', 'mail.ru', 'mailinator.com', 'live.com'):
            invalid_data = base_data.copy()
            invalid_data['email'] = u"foo@%s" % domain
            form = forms.RegistrationFormNoFreeEmail(data=invalid_data)
            self.failIf(form.is_valid())
            self.assertEqual(form.errors['email'], [u"Registration using free email addresses is prohibited. Please supply a different email address."])

        base_data['email'] = 'foo@example.com'
        form = forms.RegistrationFormNoFreeEmail(data=base_data)
        self.failUnless(form.is_valid())

class DefaultRegistrationBackendTests(TestCase):
    """
    Test the default registration backend.

    Running these tests successfull will require two templates to be
    created for the sending of activation emails; details on these
    templates and their contexts may be found in the documentation for
    the default backend. The setting ``ACCOUNT_ACTIVATION_DAYS`` must
    also be specified, and must be an integer.

    """
    def setUp(self):
        """
        Create an instance of the default backend for use in testing,
        and set ``ACCOUNT_ACTIVATION_DAYS``.

        """
        from registration.backends.default import DefaultBackend
        self.backend = DefaultBackend()
        self.old_activation = getattr(settings, 'ACCOUNT_ACTIVATION_DAYS', None)
        settings.ACCOUNT_ACTIVATION_DAYS = 7

    def tearDown(self):
        """
        Restore the original value of ``ACCOUNT_ACTIVATION_DAYS``.

        """
        settings.ACCOUNT_ACTIVATION_DAYS = self.old_activation

    def test_registration(self):
        """
        Test the registration process: registration creates a new
        inactive account and a new profile with activation key,
        populates the correct account data and sends an activation
        email.

        """
        new_user = self.backend.register({}, username='bob', email='bob@example.com', password1='secret')
        self.assertEqual(new_user.username, 'bob')
        self.failUnless(new_user.check_password('secret'))
        self.assertEqual(new_user.email, 'bob@example.com')
        self.failIf(new_user.is_active)
        self.assertEqual(RegistrationProfile.objects.count(), 1)
        self.assertEqual(len(mail.outbox), 1)

    def test_activation(self):
        """
        Test the activation process: activating within the permitted
        window sets the account's ``is_active`` field to ``True`` and
        resets the activation key, while failing to activate within
        the permitted window forbids later activation.

        """
        # First, test with a user activating inside the activation
        # window.
        valid_user = self.backend.register({}, username='alice', email='alice@example.com', password1='swordfish')
        valid_profile = RegistrationProfile.objects.get(user=valid_user)
        activated = self.backend.activate({}, valid_profile.activation_key)
        self.assertEqual(activated.username, valid_user.username)
        self.failUnless(activated.is_active)

        # Fetch the profile again to verify its activation key has
        # been reset.
        valid_profile = RegistrationProfile.objects.get(user=valid_user)
        self.assertEqual(valid_profile.activation_key, RegistrationProfile.ACTIVATED)

        # Now test again, but with a user activating outside the
        # activation window.
        expired_user = self.backend.register({}, username='bob', email='bob@example.com', password1='secret')
        expired_user.date_joined = expired_user.date_joined - datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
        expired_user.save()
        expired_profile = RegistrationProfile.objects.get(user=expired_user)
        self.failIf(self.backend.activate({}, expired_profile.activation_key))
        self.failUnless(expired_profile.activation_key_expired())

    def test_allow(self):
        """
        Test that the setting ``REGISTRATION_OPEN`` appropriately
        controls whether registration is permitted.

        """
        old_allowed = getattr(settings, 'REGISTRATION_OPEN', True)
        settings.REGISTRATION_OPEN = True
        self.failUnless(self.backend.registration_allowed({}))
        settings.REGISTRATION_OPEN = False
        self.failIf(self.backend.registration_allowed({}))
        settings.REGISTRATION_OPEN = old_allowed

    def test_form_class(self):
        """
        Test that the default form class returned is
        ``registration.forms.RegistrationForm``.

        """
        self.failUnless(self.backend.get_form_class({}) is forms.RegistrationForm)

    def test_post_registration_redirect(self):
        """
        Test that the default post-registration redirect is the named
        pattern ``registration_complete``.

        """
        self.assertEqual(self.backend.post_registration_redirect({}, User()),
                         'registration_complete')

class BackendRetrievalTests(TestCase):
    """
    Test that utilities for retrieving the active backend work
    properly.

    """
    def test_get_backend(self):
        """
        Set ``REGISTRATION_BACKEND`` temporarily, then verify that
        ``get_backend()`` returns the correct value.

        """
        from registration import get_backend
        from registration.backends.default import DefaultBackend

        # Stash away the original value of the setting so we can
        # restore it again later.
        old_backend = getattr(settings, 'REGISTRATION_BACKEND', None)

        settings.REGISTRATION_BACKEND = 'registration.backends.default.DefaultBackend'
        self.failUnless(isinstance(get_backend(), DefaultBackend))

        settings.REGISTRATION_BACKEND = old_backend

    def test_backend_error(self):
        """
        Test that an invalid or nonexistent value for the
        ``REGISTRATION_BACKEND`` setting raises the correct exception.

        """
        from registration import get_backend

        old_backend = getattr(settings, 'REGISTRATION_BACKEND', None)

        settings.REGISTRATION_BACKEND = None
        self.assertRaises(ImproperlyConfigured, get_backend)

        # Test nonexistent module
        settings.REGISTRATION_BACKEND = 'registration.backends.doesnotexist.NonExistentBackend'
        self.assertRaises(ImproperlyConfigured, get_backend)

        settings.REGISTRATION_BACKEND = old_backend

class RegistrationViewTests(TestCase):
    """
    Test the registration views.

    """
    urls = 'registration.backends.default.urls'

    def setUp(self):
        """
        Set ``REGISTRATION_BACKEND`` to the default backend, and store
        the original value to be restored later.

        """
        self.old_backend = getattr(settings, 'REGISTRATION_BACKEND', None)
        settings.REGISTRATION_BACKEND = 'registration.backends.default.DefaultBackend'
        self.old_activation = getattr(settings, 'ACCOUNT_ACTIVATION_DAYS', None)
        settings.ACCOUNT_ACTIVATION_DAYS = 7

    def tearDown(self):
        """
        Retore the original value of ``REGISTRATION_BACKEND``.

        """
        settings.REGISTRATION_BACKEND = self.old_backend
        settings.ACCOUNT_ACTIVATION_DAYS = self.old_activation

    def test_registration_view(self):
        """
        Call the ``register`` view and ensure that it properly
        validates data and creates a new user.

        """
        response = self.client.post(reverse('registration_register'),
                                    data={ 'username': 'alice',
                                           'email': 'alice@example.com',
                                           'password1': 'swordfish',
                                           'password2': 'swordfish' })
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], 'http://testserver%s' % reverse('registration_complete'))
        self.assertEqual(len(mail.outbox), 1)

    def test_activation_view(self):
        """
        Call the ``activate`` view and ensure that it properly
        activates users within the valid activation window, but not
        otherwise.

        """
        # First, register an account.
        self.client.post(reverse('registration_register'),
                         data={ 'username': 'alice',
                                'email': 'alice@example.com',
                                'password1': 'swordfish',
                                'password2': 'swordfish' })
        profile = RegistrationProfile.objects.get(user__username='alice')
        response = self.client.get(reverse('registration_activate',
                                           kwargs={ 'activation_key': profile.activation_key }))
        self.assertEqual(response.status_code, 200)

        self.failUnless(User.objects.get(username='alice').is_active)

        # Register another one and reset its date_joined to be outside
        # the activation window.
        self.client.post(reverse('registration_register'),
                         data={ 'username': 'bob',
                                'email': 'bob@example.com',
                                'password1': 'secret',
                                'password2': 'secret' })
        expired_user = User.objects.get(username='bob')
        expired_user.date_joined = expired_user.date_joined - datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
        expired_user.save()

        expired_profile = RegistrationProfile.objects.get(user=expired_user)
        response = self.client.get(reverse('registration_activate',
                                           kwargs={ 'activation_key': expired_profile.activation_key }))
        self.assertEqual(response.status_code, 200)
        self.failIf(User.objects.get(username='bob').is_active)
<|endoftext|>


<commit_before>from django.shortcuts import redirect
from django.shortcuts import render
from django.views.decorators.cache import never_cache
from django.contrib.auth.decorators import permission_required

from registration.backends import get_backend

def register(request, backend='default', template_name='registration/registration_form.html'):
    backend = get_backend(backend)

    # determine is registration is currently allowed. the ``request`` object
    # is passed which can be used to selectively disallow registration based on
    # the user-agent
    if not backend.registration_allowed(request):
        return redirect(*backend.registration_closed_redirect(request))

    form_class = backend.get_registration_form_class(request)

    if request.method == 'POST':
        form = form_class(request.POST, request.FILES)

        if form.is_valid():
            user = backend.register(request, form)
            return redirect(backend.post_registration_redirect(request, user))
    else:
        form = form_class()

    return render(request, template_name, {'form': form})

@never_cache
def verify(request, backend='default', template_name='registration/registration_verify.html', **kwargs):
    backend = get_backend(backend)
    profile = backend.get_profile(request, **kwargs)

    if profile:
        # check to see if moderation for this profile is required and whether or
        # not it is a verified account.
        if backend.moderation_required(request, profile):
            moderation_required = True
            backend.verify(request, profile, **kwargs)
        else:
            moderation_required = False
            # attempt to activate this user
            backend.activate(request, profile, **kwargs)
    else:
        moderation_required = None

    return render(request, template_name, {
        'profile': profile,
        'moderation_required': moderation_required,
    })

@never_cache
def moderate(request, backend='default', template_name='registration/registration_moderate.html', **kwargs):
    backend = get_backend(backend)
    profile = backend.get_profile(request, **kwargs)
    form_class = backend.get_moderation_form_class(request)

    if request.method == 'POST':
        form = form_class(request.POST)

        if form.is_valid():
            backend.moderate(request, form, profile, **kwargs)
            return redirect(backend.post_moderation_redirect(request, profile))
    else:
        form = form_class()

    return render(request, template_name, {
        'form': form,
        'profile': profile,
    })

@permission_required('registration.change_registrationprofile')
def moderate_list(request, backend='default', template_name='registration/registration_moderate_list.html'):
    backend = get_backend(backend)
    profiles = backend.get_unmoderated_profiles(request)

    return render(request, template_name, {
        'profiles': profiles,
    })
<commit_msg>Require login for account moderation<commit_after>from django.shortcuts import redirect
from django.shortcuts import render
from django.views.decorators.cache import never_cache
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.decorators import login_required
from registration.backends import get_backend

def register(request, backend='default', template_name='registration/registration_form.html'):
    backend = get_backend(backend)

    # determine is registration is currently allowed. the ``request`` object
    # is passed which can be used to selectively disallow registration based on
    # the user-agent
    if not backend.registration_allowed(request):
        return redirect(*backend.registration_closed_redirect(request))

    form_class = backend.get_registration_form_class(request)

    if request.method == 'POST':
        form = form_class(request.POST, request.FILES)

        if form.is_valid():
            user = backend.register(request, form)
            return redirect(backend.post_registration_redirect(request, user))
    else:
        form = form_class()

    return render(request, template_name, {'form': form})

@never_cache
def verify(request, backend='default', template_name='registration/registration_verify.html', **kwargs):
    backend = get_backend(backend)
    profile = backend.get_profile(request, **kwargs)

    if profile:
        # check to see if moderation for this profile is required and whether or
        # not it is a verified account.
        if backend.moderation_required(request, profile):
            moderation_required = True
            backend.verify(request, profile, **kwargs)
        else:
            moderation_required = False
            # attempt to activate this user
            backend.activate(request, profile, **kwargs)
    else:
        moderation_required = None

    return render(request, template_name, {
        'profile': profile,
        'moderation_required': moderation_required,
    })

@never_cache
@login_required()
def moderate(request, backend='default', template_name='registration/registration_moderate.html', **kwargs):
    backend = get_backend(backend)
    profile = backend.get_profile(request, **kwargs)
    form_class = backend.get_moderation_form_class(request)

    if request.method == 'POST':
        form = form_class(request.POST)

        if form.is_valid():
            backend.moderate(request, form, profile, **kwargs)
            return redirect(backend.post_moderation_redirect(request, profile))
    else:
        form = form_class()

    return render(request, template_name, {
        'form': form,
        'profile': profile,
    })

@permission_required('registration.change_registrationprofile')
@login_required()
def moderate_list(request, backend='default', template_name='registration/registration_moderate_list.html'):
    backend = get_backend(backend)
    profiles = backend.get_unmoderated_profiles(request)

    return render(request, template_name, {
        'profiles': profiles,
    })
<|endoftext|>


<commit_before>from django.conf import settings
from django.contrib import messages
from django.contrib.auth import login
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse

from .forms import RegistrationForm
from .models import RegistrationProfile

def register(request,form=RegistrationForm):
    form = form(request,request.POST or None)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse('registration_complete'))
    values = { 'form': form }
    return TemplateResponse(request,'registration/registration_form.html',values)

def activate(request,activation_key):
    profile, activated = RegistrationProfile.objects.get_and_activate(activation_key)
    if activated: # success! login
        user = profile.user
        user.backend='django.contrib.auth.backends.ModelBackend'
        login(request,user)
        m = "Welcome %s. Your account has been activated and you have been logged in."%user
        messages.success(request,m)
        return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
    values = {
        'profile': profile,
    }
    return TemplateResponse(request,'registration/activate.html',values)
<commit_msg>RegistrationForm no longer takes in request.POST<commit_after>from django.conf import settings
from django.contrib import messages
from django.contrib.auth import login
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse

from .forms import RegistrationForm
from .models import RegistrationProfile

def register(request,form=RegistrationForm):
    form = form(request)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse('registration_complete'))
    values = { 'form': form }
    return TemplateResponse(request,'registration/registration_form.html',values)

def activate(request,activation_key):
    profile, activated = RegistrationProfile.objects.get_and_activate(activation_key)
    if activated: # success! login
        user = profile.user
        user.backend='django.contrib.auth.backends.ModelBackend'
        login(request,user)
        m = "Welcome %s. Your account has been activated and you have been logged in."%user
        messages.success(request,m)
        return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
    values = {
        'profile': profile,
    }
    return TemplateResponse(request,'registration/activate.html',values)
<|endoftext|>