views.py 10.3 KB
Newer Older
1 2 3
# standard library imports
from __future__ import absolute_import, print_function
from distutils.util import strtobool
4
from datetime import date
5
# core django imports
6
from django.shortcuts import redirect
Daniel W Bond's avatar
pep8 me  
Daniel W Bond committed
7
from django.views.generic import FormView
8 9 10 11 12 13
from django.core.urlresolvers import reverse
from django.contrib import messages
# third party imports
from braces.views import LoginRequiredMixin
from ratelimit.decorators import ratelimit
# imports from your apps
14
from accounts.models import Student, Confirmation, Major
15
from accounts.views import create_email, no_nums
16 17 18
from housing.models import Room
from .forms import (WelcomeNameForm, WelcomeMajorForm,
                    WelcomePrivacyForm, WelcomeSocialForm)
Daniel W Bond's avatar
Daniel W Bond committed
19

20 21 22 23 24

settings_redirect = """You've already finished the welcome walkthrough.
                       Your user settings can now be changed here on this page."""


25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
def get_semester(date):
    # months are between 1 and 12, inclusive
    semesters = {
        'Spring': (1, 2, 3, 4, 5),
        'Summer': (6, 7),
        'Fall': (8, 9, 10, 11, 12)
    }

    for semester, months in semesters.iteritems():
        if date.month in months:
            semester_string = semester

    return semester_string


40
class WelcomeName(LoginRequiredMixin, FormView):
Daniel W Bond's avatar
Daniel W Bond committed
41 42
    """Student adds first and last name, and gender and gender display."""

43 44 45 46
    template_name = 'welcome_name.html'
    form_class = WelcomeNameForm
    login_url = 'login'

Daniel W Bond's avatar
Daniel W Bond committed
47 48
    # students are redirected to the normal settings page once they have completed
    # the welcome walkthrough in its entirety
49 50 51 52
    def get(self, request, *args, **kwargs):

        if self.request.user.student.totally_done():
            messages.add_message(request, messages.INFO, settings_redirect)
53
            return redirect(reverse('update_student',
Daniel W Bond's avatar
pep8 me  
Daniel W Bond committed
54
                            kwargs={'slug': self.request.user.username}))
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
        else:
            return super(WelcomeName, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(WelcomeName, self).get_context_data(**kwargs)

        me = Student.objects.get(user=self.request.user)

        form = WelcomeNameForm(initial={'first_name': me.user.first_name,
                                        'last_name': me.user.last_name,
                                        'gender': me.gender,
                                        'show_gender': me.show_gender, })

        form.fields['first_name'].widget.attrs['class'] = 'form-control'
        form.fields['last_name'].widget.attrs['class'] = 'form-control'

        context['my_form'] = form
        return context

    @ratelimit(key='user', rate='5/m', method='POST', block=True)
    @ratelimit(key='user', rate='10/d', method='POST', block=True)
    def post(self, request, *args, **kwargs):
        return super(WelcomeName, self).post(request, *args, **kwargs)

    def form_valid(self, form):
        me = Student.objects.get(user=self.request.user)

82 83
        me.user.first_name = no_nums(form.data['first_name'])
        me.user.last_name = no_nums(form.data['last_name'])
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

        me.gender = form.data.getlist('gender')
        me.show_gender = strtobool(form.data.get('show_gender', 'False'))

        me.completedName = True

        me.user.save()
        me.save()

        return super(WelcomeName, self).form_valid(form)

    def get_success_url(self):
        return reverse('welcomePrivacy')


class WelcomePrivacy(LoginRequiredMixin, FormView):
Daniel W Bond's avatar
Daniel W Bond committed
100 101
    """Student adds off-or-on campus status, and if on-campus, housing and privacy."""

102 103 104 105 106 107 108 109
    form_class = WelcomePrivacyForm
    template_name = 'welcome_privacy.html'
    login_url = 'login'

    def get(self, request, *args, **kwargs):

        if self.request.user.student.totally_done():
            messages.add_message(request, messages.INFO, settings_redirect)
110
            return redirect(reverse('update_student',
Daniel W Bond's avatar
pep8 me  
Daniel W Bond committed
111
                            kwargs={'slug': self.request.user.username}))
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 140 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 166 167 168 169 170 171 172 173 174
        else:
            return super(WelcomePrivacy, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(WelcomePrivacy, self).get_context_data(**kwargs)

        me = Student.objects.get(user=self.request.user)

        form = WelcomePrivacyForm(initial={'on_campus': me.on_campus,
                                           'privacy': me.privacy, })

        form.fields['room'].widget.user = self.request.user

        context['my_form'] = form

        context['student'] = me

        return context

    @ratelimit(key='user', rate='5/m', method='POST', block=True)
    @ratelimit(key='user', rate='10/d', method='POST', block=True)
    def post(self, request, *args, **kwargs):
        return super(WelcomePrivacy, self).post(request, *args, **kwargs)

    def form_valid(self, form):
        me = Student.objects.get(user=self.request.user)

        current_room = me.room

        # if you somehow got around the hidden widget, you're still outta luck
        if me.recent_changes() > 2:
            form_room = current_room
        else:
            try:
                form_room = Room.objects.get(pk=form.data['room'])
            except:
                form_room = None

        # casts to an integer, 0 or 1
        on_campus = strtobool(form.data.get('on_campus', 'True'))

        # no room if you move off campus
        if not on_campus:
            form_room = None

        if current_room != form_room:
            form.instance.times_changed_room += 1
            Confirmation.objects.filter(student=me).delete()

        me.on_campus = on_campus
        me.room = form_room

        me.completedPrivacy = True

        me.save()

        return super(WelcomePrivacy, self).form_valid(form)

    def get_success_url(self):
        return reverse('welcomeMajor')


class WelcomeMajor(LoginRequiredMixin, FormView):
Daniel W Bond's avatar
Daniel W Bond committed
175 176
    """Student adds major and graduation year."""

177 178 179 180 181 182 183 184
    template_name = 'welcome_major.html'
    form_class = WelcomeMajorForm
    login_url = 'login'

    def get(self, request, *args, **kwargs):

        if self.request.user.student.totally_done():
            messages.add_message(request, messages.INFO, settings_redirect)
185
            return redirect(reverse('update_student',
Daniel W Bond's avatar
pep8 me  
Daniel W Bond committed
186
                            kwargs={'slug': self.request.user.username}))
187 188 189 190 191 192 193 194
        else:
            return super(WelcomeMajor, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(WelcomeMajor, self).get_context_data(**kwargs)

        me = Student.objects.get(user=self.request.user)

195
        form = WelcomeMajorForm(initial={'major': me.major.all(),
196 197
                                         'graduating_year': me.graduating_year, })

198
        form.fields['major'].widget.attrs['class'] = 'chosen-select'
199

200
        context['my_form'] = form
201 202 203 204 205 206 207 208 209 210 211 212 213
        context['student'] = me

        return context

    @ratelimit(key='user', rate='5/m', method='POST', block=True)
    @ratelimit(key='user', rate='10/d', method='POST', block=True)
    def post(self, request, *args, **kwargs):
        return super(WelcomeMajor, self).post(request, *args, **kwargs)

    def form_valid(self, form):

        me = Student.objects.get(user=self.request.user)

214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
        try:
            # see UpdateStudent in accounts/ for a detailed explanation
            # but m2m fields are more difficult to manage than other relationships
            form_major_pks = set(form.data.getlist('major')[:2])
            form_majors = [Major.objects.get(pk=pk) for pk in form_major_pks]
            # a student likely won't have any majors on the welcome walkthrough
            # using Python's implicit evaluation (empty is False, anything is True)
            if me.major.all():
                for current_major in me.major.all():
                    if current_major not in form_majors:
                        me.major.remove(current_major)
            for form_major in form_majors:
                if form_major not in me.major.all():
                    me.major.add(form_major)
        except:
            pass

231 232 233 234 235 236 237 238 239 240 241 242 243
        me.graduating_year = form.instance.graduating_year

        me.completedMajor = True

        me.save()

        return super(WelcomeMajor, self).form_valid(form)

    def get_success_url(self):
        return reverse('welcomeSocial')


class WelcomeSocial(LoginRequiredMixin, FormView):
Daniel W Bond's avatar
Daniel W Bond committed
244 245
    """Student connects social media accounts. Redirects to settings page when done."""

246 247 248 249 250 251 252 253
    form_class = WelcomeSocialForm
    template_name = 'welcome_social.html'
    login_url = 'login'

    def get(self, request, *args, **kwargs):

        if self.request.user.student.totally_done():
            messages.add_message(request, messages.INFO, settings_redirect)
254
            return redirect(reverse('update_student',
Daniel W Bond's avatar
pep8 me  
Daniel W Bond committed
255
                            kwargs={'slug': self.request.user.username}))
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
        else:
            return super(WelcomeSocial, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(WelcomeSocial, self).get_context_data(**kwargs)

        me = Student.objects.get(user=self.request.user)

        context['student'] = me

        return context

    @ratelimit(key='user', rate='5/m', method='POST', block=True)
    @ratelimit(key='user', rate='10/d', method='POST', block=True)
    def post(self, request, *args, **kwargs):
        return super(WelcomeSocial, self).post(request, *args, **kwargs)

    def form_valid(self, form):
        me = Student.objects.get(user=self.request.user)

        me.completedSocial = True

        me.save()

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        # send students a welcome email
        text_path = 'email/welcome.txt'
        html_path = 'email/welcome.html'

        today = date.today()
        semester = "%s %s" % (get_semester(today), today.strftime('%Y'))

        context = {
            'student_name': me.get_first_name_or_uname,
            'semester': semester
        }

        subject = "Welcome to Roomlist, %s" % me.get_first_name_or_uname()
        to = me.user.email

        welcome_email = create_email(text_path, html_path, subject, to, context)

        welcome_email.send()

299 300 301 302 303 304 305 306 307
        return super(WelcomeSocial, self).form_valid(form)

    def get_success_url(self):

        if self.request.user.student.totally_done():
            messages.add_message(self.request, messages.SUCCESS,
                                 "You successfully finished the welcome walkthrough!")

        return reverse('detail_student',
Daniel W Bond's avatar
pep8 me  
Daniel W Bond committed
308
                       kwargs={'slug': self.request.user.username})