views.py 6.48 KB
Newer Older
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
1
2
3
4
5
6
7
8
9
10
11
import logging

from django import forms
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash, authenticate, login, get_user_model
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import PasswordChangeForm
from django.core.mail import send_mail
from django.db.models import ProtectedError
from django.forms import widgets
12
from django.http import HttpResponseForbidden
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from django.shortcuts import render, redirect
from django.template import TemplateDoesNotExist
from django.utils.translation import ugettext

from basetheme_bootstrap import user_preferences
from basetheme_bootstrap.forms import UserCreationFormWithMore, \
    MyUserChangeForm, UserDeleteForm

logger = logging.getLogger(__name__)


def about_page(request):
    context = {}
    try:
        return render(request, settings.BASETHEME_BOOTSTRAP_TEMPLATE_LOCATION_PROJECT + '/about.html')
    except TemplateDoesNotExist:
        return render(request, 'basetheme_bootstrap/about.example.html')


@login_required
def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Your password was successfully updated!')
            return redirect('basetheme_bootstrap:account')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'registration/small_form_host.html', {
        'title': ugettext('Change password'),
        'submit_text': ugettext('Save changes'),
        'form': form
    })


def signup(request):
    if request.method == 'POST':
        form = UserCreationFormWithMore(request.POST)
        if form.is_valid():
            user = form.save()
            if get_user_model().objects.filter(pk__gt=1).count() == 0:
                user.is_superuser = True
                user.is_staff = True
                user.save()
61
            username = user.username
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            request.user = user

            try:
                send_mail(
                    subject=ugettext('Account successfully created'),
                    message=ugettext(
                        'Dear %(first_name)s %(last_name)s\n\n'
                        'Your account have successfully been created on %(joined)s.\n\nBest regards') % dict(
                        first_name=request.user.first_name,
                        last_name=request.user.last_name,
                        joined=str(request.user.date_joined),
                    ),
                    from_email=settings.DEFAULT_FROM_EMAIL,
                    recipient_list=[request.user.email],
                    fail_silently=False,
                )
            except Exception as e:
                logging.exception("Sending email to user %i failed" % user.pk)

            login(request, user)
            return redirect('home')
    else:
86
87
        if not request.user.is_anonymous:
            return HttpResponseForbidden()
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
        form = UserCreationFormWithMore()
    return render(request, 'registration/signup.html', {'form': form})


def user_update(request):
    if request.method == 'POST':
        form = MyUserChangeForm(instance=request.user, data=request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Your account was successfully updated!')
            return redirect('basetheme_bootstrap:account')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = MyUserChangeForm(instance=request.user)
    return render(request, 'registration/small_form_host.html', {
        'title': ugettext('Update account'),
        'submit_text': ugettext('Save changes'),
        'form': form,
        'medium_width': True,
    })


def user_delete(request):
    if request.method == 'POST':
        form = UserDeleteForm(instance=request.user, data=request.POST)
        if form.is_valid():
            try:
                user = form.save()
                user.delete()
                update_session_auth_hash(request, user)  # Important!
                messages.success(request, 'Your account was successfully deleted!')
                return redirect('/')
            except ProtectedError as e:
                messages.error(request, ugettext("Some data remaining in the system prevent the deletion of your "
                                                 "account. Please either remove these data, or contact the "
                                                 "administrator to solve the issue.\nMessage:\n" + str(e)))
            except Exception as e:
                messages.error(request, e)
    else:
        form = UserDeleteForm(instance=request.user)
    return render(request, 'registration/small_form_host.html', {
        'title': ugettext('Account deletion'),
        'submit_text': ugettext('Delete account and all related data'),
        'form': form,
        'medium_width': True,
        'btn_classes': 'btn-lg btn-danger text-center',
        'btn_container_classes': 'text-center',
    })


140
@login_required
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def account_detail(request):
    klass = user_preferences.get_user_preference_class()
    if klass is None:
        form_prefs = None
    else:
        is_posted = request.method == 'POST'
        pref = klass.get_for_user(user=request.user)
        form_prefs = forms.modelform_factory(
            klass,
            fields=list(klass.get_allowed_fields()),
        )(instance=pref, data=request.POST if is_posted else None)
        if is_posted and form_prefs.is_valid():
            form_prefs.save()
            form_prefs = forms.modelform_factory(
                klass,
                fields=list(klass.get_allowed_fields()),
            )(instance=klass.get_for_user(user=request.user))
        # dirty patch for time field (don't know why django doesn't express the correct type by default)
        for f in form_prefs.fields.values():
            if isinstance(f.widget, widgets.TimeInput):
                f.widget.input_type = 'time'
    return render(request, 'registration/account.html', {
        'form_prefs': form_prefs,
        'btn_classes': 'pull-right float-right'
    })