Project

General

Profile

Download (5.74 KB) Statistics
| Branch: | Tag: | Revision:

root / uauth / organization / views.py @ 64438aee

1
import csv
2
import datetime
3

    
4
from django.utils.translation import ugettext as _
5
from django.core.urlresolvers import reverse_lazy
6
from django.shortcuts import render, redirect
7

    
8
from django.views.generic.base import TemplateView
9
from django.views.generic.list import ListView
10
from django.views.generic.edit import FormView, UpdateView
11
from django.views.generic import DetailView, View
12
from django.contrib import messages
13

    
14
from django_tables2 import RequestConfig
15

    
16
from .utils import create_user, create_or_update_users
17
from .models import LocalAccount, Organization
18
from .forms import LocalAccountCreateForm, LocalAccountForm, UsersImportForm
19
from .tables import AccountTable
20

    
21

    
22
class OrganizationMixin(object):
23

    
24
    def get_queryset(self):
25
        qs = super(OrganizationMixin, self).get_queryset()
26
        return qs.filter(organization__slug=self.kwargs['organization_slug'])
27

    
28
    def get_success_url(self):
29
        return reverse_lazy('manage-users', kwargs={'organization_slug': self.kwargs['organization_slug']})
30

    
31
    def get_context_data(self, *args, **kwargs):
32
        ctx = super(OrganizationMixin, self).get_context_data(*args, **kwargs)
33
        ctx['organization'] = Organization.objects.get(slug=self.kwargs['organization_slug'])
34
        return ctx
35

    
36
class ManageView(TemplateView):
37
    template_name = 'organization/manage.html'
38

    
39
manage = ManageView.as_view()
40

    
41
class UsersPageView(OrganizationMixin, ListView):
42
    template_name = 'organization/users.html'
43
    model = LocalAccount
44

    
45
    def get_context_data(self, *args, **kwargs):
46
        context = super(UsersPageView, self).get_context_data(*args, **kwargs)
47
        table = AccountTable(context['object_list'])
48
        RequestConfig(self.request).configure(table)
49
        context['table'] = table
50
        return context
51

    
52
users = UsersPageView.as_view()
53

    
54

    
55
class UsersCreateView(OrganizationMixin, FormView):
56
    template_name = 'organization/create-users.html'
57
    form_class = LocalAccountCreateForm
58

    
59
    def form_valid(self, form):
60
        data = form.cleaned_data
61
        data['organization'] = Organization.objects.get(slug=self.kwargs['organization_slug'])
62
        accounts_number = data.pop('accounts_number')
63
        accounts_number_start = data.pop('accounts_number_start')
64
        if accounts_number_start < 1:
65
            accounts_number_start = 0
66

    
67
        username = data['username']
68
        if accounts_number > 1:
69
            for index in xrange(accounts_number_start, accounts_number + accounts_number_start):
70
                data['username'] = '%s-%s' % (username, index)
71
                if not create_user(data):
72
                    messages.error(self, request, _('Error while creating user %s' % data['username']))
73
                    break
74
            messages.info(self.request, _('%s users added successfully' % accounts_number))
75
        else:
76
            if create_user(data):
77
                messages.info(self.request, _('User "%s" successfully created' % data['username']))
78
            else:
79
                messages.error(self.request, _('Error occured while creating user "%s"' % data['username']))
80
        return super(UsersCreateView, self).form_valid(form)
81

    
82
create_users = UsersCreateView.as_view()
83

    
84

    
85
class ShowUserView(OrganizationMixin, DetailView):
86
    model = LocalAccount
87
    template_name = 'organization/view_user.html'
88

    
89
view_user = ShowUserView.as_view()
90

    
91

    
92
class UserEditView(OrganizationMixin, UpdateView):
93
    template_name = 'organization/edit_user.html'
94
    model = LocalAccount
95
    form_class = LocalAccountForm
96

    
97
    def form_valid(self, form):
98
        username = self.object.username
99
        if 'delete' in self.request.POST:
100
            self.object.delete()
101
            messages.info(self.request, _('Account "%s" successfully deleted' % username))
102
            return redirect(self.get_success_url())
103
        else:
104
            messages.info(self.request, _('Account "%s" successfully updated' % username))
105
            return super(UserEditView, self).form_valid(form)
106

    
107
edit_user = UserEditView.as_view()
108

    
109

    
110
class ImportUsersView(OrganizationMixin, TemplateView):
111
    form_class = UsersImportForm
112
    template_name = 'organization/import_users.html'
113

    
114
    def get_context_data(self, **kwargs):
115
        ctx = super(ImportUsersView, self).get_context_data(**kwargs)
116
        ctx['form'] = self.form_class()
117
        return ctx
118

    
119
    def post(self, request, *args, **kwargs):
120
        form = self.form_class(request.POST, request.FILES)
121
        context = self.get_context_data(**kwargs)
122
        context['form'] = form
123
        if form.is_valid():
124
            data = form.cleaned_data['users_file']
125
            dialect = csv.Sniffer().sniff(data.read(1024))
126
            data.seek(0)
127
            reader = csv.reader(data, dialect)
128
            reader.next()
129
            users = []
130
            for row in reader:
131
                try:
132
                    user = {'username': row[0].strip(),
133
                            'first_name': row[1].strip(),
134
                            'last_name': row[2].strip(),
135
                            'password': row[4].strip(),
136
                            'organization': context['organization']
137
                        }
138
                except IndexError:
139
                    # ignore wrong lines
140
                    continue
141
                try:
142
                    user['expiration_date'] = datetime.datetime.strptime(row[3], '%Y-%m-%d')
143
                except ValueError:
144
                    pass
145
                users.append(user)
146
            created, updated = create_or_update_users(users)
147
            if created:
148
                messages.info(request, _('%s accounts added' % created))
149
            if updated:
150
                messages.info(request, _('%s accounts updated' % updated))
151
            return redirect(self.get_success_url())
152
        else:
153
            return self.render_to_response(context)
154

    
155
import_users = ImportUsersView.as_view()
(9-9/9)