views.py 4.22 KB
Newer Older
1 2
from django.shortcuts import render
from django.views.generic.edit import UpdateView, CreateView
Skia's avatar
Skia committed
3
from django.views.generic.base import View
4 5 6
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import IntegrityError
7 8 9 10
from django import forms
from django.forms import Select
from django.conf import settings

11
from ajax_select.fields import AutoCompleteSelectField
Skia's avatar
Skia committed
12
import random
13

14
from subscription.models import Subscriber, Subscription
15
from core.views import CanEditMixin, CanEditPropMixin, CanViewMixin
Skia's avatar
Skia committed
16 17
from core.models import User

Skia's avatar
Skia committed
18 19 20
def get_subscriber(user):
    s = Subscriber.objects.filter(pk=user.pk).first()
    return s
21 22 23 24

class SubscriptionForm(forms.ModelForm):
    class Meta:
        model = Subscription
Skia's avatar
Skia committed
25
        fields = ['member', 'subscription_type', 'payment_method', 'location']
26
    member = AutoCompleteSelectField('users', required=False, help_text=None)
27

28 29 30 31 32 33 34 35
    def __init__(self, *args, **kwargs):
        super(SubscriptionForm, self).__init__(*args, **kwargs)
        # Add fields to allow basic user creation
        self.fields['last_name'] = forms.CharField(max_length=User._meta.get_field('last_name').max_length)
        self.fields['first_name'] = forms.CharField(max_length=User._meta.get_field('first_name').max_length)
        self.fields['email'] = forms.EmailField()
        self.fields.move_to_end('subscription_type')
        self.fields.move_to_end('payment_method')
Skia's avatar
Skia committed
36
        self.fields.move_to_end('location')
37

38 39 40 41 42 43
    def clean_member(self):
        subscriber = self.cleaned_data.get("member")
        if subscriber:
            subscriber = Subscriber.objects.filter(id=subscriber.id).first()
        return subscriber

44 45 46 47 48 49 50 51 52 53 54 55 56 57
    def clean(self):
        cleaned_data = super(SubscriptionForm, self).clean()
        if (cleaned_data.get("member") is None
                and "last_name" not in self.errors.as_data()
                and "first_name" not in self.errors.as_data()
                and "email" not in self.errors.as_data()):
            self.errors.pop("member", None)
            if Subscriber.objects.filter(email=cleaned_data.get("email")).first() is not None:
                self.add_error("email", ValidationError(_("A user with that email address already exists")))
            else:
                u = Subscriber(last_name = self.cleaned_data.get("last_name"),
                        first_name = self.cleaned_data.get("first_name"),
                        email = self.cleaned_data.get("email"))
                u.generate_username()
Skia's avatar
Skia committed
58
                u.set_password(str(random.randrange(1000000, 10000000)))
59 60 61 62 63 64 65 66 67 68 69 70
                u.save()
                cleaned_data["member"] = u
        elif cleaned_data.get("member") is not None:
            self.errors.pop("last_name", None)
            self.errors.pop("first_name", None)
            self.errors.pop("email", None)
        if cleaned_data.get("member") is None:
            # This should be handled here, but it is done in the Subscription model's clean method
            # TODO investigate why!
            raise ValidationError(_("You must either choose an existing user or create a new one properly"))
        return cleaned_data

Skia's avatar
Skia committed
71
class NewSubscription(CreateView):
Skia's avatar
Skia committed
72
    template_name = 'subscription/subscription.jinja'
73
    form_class = SubscriptionForm
Skia's avatar
Skia committed
74

Skia's avatar
Skia committed
75 76 77 78 79 80
    def dispatch(self, request, *arg, **kwargs):
        res = super(NewSubscription, self).dispatch(request, *arg, **kwargs)
        if request.user.is_in_group(settings.SITH_MAIN_BOARD_GROUP):
            return res
        raise PermissionDenied

Skia's avatar
Skia committed
81 82
    def get_initial(self):
        if 'member' in self.request.GET.keys():
Skia's avatar
Skia committed
83 84
            return {'member': self.request.GET['member'], 'subscription_type': 'deux-semestres'}
        return {'subscription_type': 'deux-semestres'}
Skia's avatar
Skia committed
85 86

    def form_valid(self, form):
87 88
        form.instance.subscription_start = Subscription.compute_start(
                duration=settings.SITH_SUBSCRIPTIONS[form.instance.subscription_type]['duration'])
Skia's avatar
Skia committed
89 90 91 92 93
        form.instance.subscription_end = Subscription.compute_end(
                duration=settings.SITH_SUBSCRIPTIONS[form.instance.subscription_type]['duration'],
                start=form.instance.subscription_start
                )
        return super(NewSubscription, self).form_valid(form)
94