Example #1
0
    def __init__(self, facility, *args, **kwargs):
        super(FacilityUserForm, self).__init__(*args, **kwargs)

        self.fields["default_language"].choices = [
            (lang_code, get_language_name(lang_code))
            for lang_code in get_installed_language_packs()
        ]

        # Select the initial default language,
        #   but only if we're not in the process of updating it to something else.
        if not self.fields[
                "default_language"].initial and "default_language" not in self.changed_data:
            self.fields["default_language"].initial = (
                self.instance
                and self.instance.default_language) or get_default_language()

        # Passwords only required on new, not on edit
        self.fields["password_first"].required = self.instance.pk == ""
        self.fields["password_recheck"].required = self.instance.pk == ""

        # Across POST and GET requests
        self.fields["zone_fallback"].initial = facility.get_zone()
        self.fields["facility"].initial = facility
        self.fields["facility"].queryset = Facility.objects.by_zone(
            facility.get_zone())
        self.fields["group"].queryset = FacilityGroup.objects.filter(
            facility=facility)
Example #2
0
def _facility_user(request, facility, title, is_teacher=False, new_user=False, user_being_edited=None):
    """
    Different codepaths for the following:
    * Django admin/teacher creates student (add_facility_student)
    * Django admin creates teacher
    * Django admin/edits a user, self, or student edits self (edit_facility_user)
    * Student creates self (facility_user_signup)

    Each has its own message and redirect.
    """
    next = request.next or request.get_full_path() or reverse("homepage")
    # Data submitted to create/edit the user.
    if request.method == "POST":

        form = FacilityUserForm(facility, data=request.POST, instance=user_being_edited)
        if not form.is_valid():
            messages.error(request, _("There was a problem saving the information provided; please review errors below."))

        else:
            # In case somebody tries to check the hidden 'is_teacher' field
            if form.cleaned_data["is_teacher"] and not request.is_admin:
                raise PermissionDenied(_("You must be a teacher to edit or create a teacher."))

            if form.cleaned_data["password_first"]:
                form.instance.set_password(form.cleaned_data["password_first"])

            form.save()

            # Editing self
            if request.session.get("facility_user") and request.session.get("facility_user").id == form.instance.id:
                messages.success(request, _("You successfully updated your user settings."))
                return HttpResponseRedirect(next)

            # Editing another user
            elif not new_user:
                messages.success(request, _("Changes saved for user '%(username)s'") % {"username": form.instance.get_name()})
                if request.next:
                    return HttpResponseRedirect(next)

            # New user created by admin
            elif request.is_admin or request.is_django_user:
                messages.success(request, _("You successfully created user '%(username)s'") % {"username": form.instance.get_name()})
                if request.next:
                    return HttpResponseRedirect(next)
                else:
                    zone_id = getattr(facility.get_zone(), "id", None)
                    return HttpResponseRedirect(reverse("facility_management", kwargs={"zone_id": zone_id, "facility_id": facility.id}))

            # New student signed up
            else:
                # Double check permissions
                messages.success(request, _("You successfully registered."))
                return HttpResponseRedirect(reverse("homepage"))

    # render form for editing
    elif user_being_edited:
        form = FacilityUserForm(facility=facility, instance=user_being_edited)

    # in all other cases, we are creating a new user
    else:
        form = FacilityUserForm(facility, initial={
            "group": request.GET.get("group"),
            "is_teacher": is_teacher,
            "default_language": get_default_language(),
        })

    if is_teacher or (not (request.is_admin or request.is_teacher) and FacilityGroup.objects.filter(facility=facility).count() == 0) or (not new_user and not (request.is_admin or request.is_teacher)):
        form.fields['group'].widget = forms.HiddenInput()
    if Facility.objects.count() < 2 or (not new_user and not request.is_admin):
        form.fields['facility'].widget = forms.HiddenInput()

    return {
        "title": title,
        "new_user": new_user,
        "form": form,
        "facility": facility,
        "teacher": is_teacher,
    }
Example #3
0
    def __init__(self, facility, *args, **kwargs):
        super(FacilityUserForm, self).__init__(*args, **kwargs)

        self.fields["default_language"].choices = [(lang_code, get_language_name(lang_code)) for lang_code in get_installed_language_packs()]

        # Select the initial default language,
        #   but only if we're not in the process of updating it to something else.
        if not self.fields["default_language"].initial and "default_language" not in self.changed_data:
            self.fields["default_language"].initial = (self.instance and self.instance.default_language) or get_default_language()

        # Passwords only required on new, not on edit
        self.fields["password_first"].required = self.instance.pk == ""
        self.fields["password_recheck"].required = self.instance.pk == ""

        # Across POST and GET requests
        self.fields["zone_fallback"].initial = facility.get_zone()
        self.fields["facility"].initial = facility
        self.fields["facility"].queryset = Facility.objects.by_zone(facility.get_zone())
        self.fields["group"].queryset = FacilityGroup.objects.filter(facility=facility)
Example #4
0
def _facility_user(request,
                   facility,
                   title,
                   is_teacher=False,
                   new_user=False,
                   user_being_edited=None):
    """
    Different codepaths for the following:
    * Django admin/teacher creates student (add_facility_student)
    * Django admin creates teacher
    * Django admin/edits a user, self, or student edits self (edit_facility_user)
    * Student creates self (facility_user_signup)

    Each has its own message and redirect.
    """
    next = request.next or request.get_full_path() or reverse("homepage")
    # Data submitted to create/edit the user.
    if request.method == "POST":

        form = FacilityUserForm(facility,
                                data=request.POST,
                                instance=user_being_edited)
        if not form.is_valid():
            messages.error(
                request,
                _("There was a problem saving the information provided; please review errors below."
                  ))

        else:
            # In case somebody tries to check the hidden 'is_teacher' field
            if form.cleaned_data["is_teacher"] and not request.is_admin:
                raise PermissionDenied(
                    _("You must be a teacher to edit or create a teacher."))

            if form.cleaned_data["password_first"]:
                form.instance.set_password(form.cleaned_data["password_first"])

            form.save()

            # Editing self
            if request.session.get("facility_user") and request.session.get(
                    "facility_user").id == form.instance.id:
                messages.success(
                    request, _("You successfully updated your user settings."))
                return HttpResponseRedirect(next)

            # Editing another user
            elif not new_user:
                messages.success(
                    request,
                    _("Changes saved for user '%(username)s'") %
                    {"username": form.instance.get_name()})
                if request.next:
                    return HttpResponseRedirect(next)

            # New user created by admin
            elif request.is_admin or request.is_django_user:
                messages.success(
                    request,
                    _("You successfully created user '%(username)s'") %
                    {"username": form.instance.get_name()})
                if request.next:
                    return HttpResponseRedirect(next)
                else:
                    zone_id = getattr(facility.get_zone(), "id", None)
                    return HttpResponseRedirect(
                        reverse("facility_management",
                                kwargs={
                                    "zone_id": zone_id,
                                    "facility_id": facility.id
                                }))

            # New student signed up
            else:
                # Double check permissions
                messages.success(request, _("You successfully registered."))
                return HttpResponseRedirect(reverse("homepage"))

    # render form for editing
    elif user_being_edited:
        form = FacilityUserForm(facility=facility, instance=user_being_edited)

    # in all other cases, we are creating a new user
    else:
        form = FacilityUserForm(facility,
                                initial={
                                    "group": request.GET.get("group"),
                                    "is_teacher": is_teacher,
                                    "default_language": get_default_language(),
                                })

    if is_teacher or (not (request.is_admin or request.is_teacher) and
                      FacilityGroup.objects.filter(facility=facility).count()
                      == 0) or (not new_user and
                                not (request.is_admin or request.is_teacher)):
        form.fields['group'].widget = forms.HiddenInput()
    if Facility.objects.count() < 2 or (not new_user and not request.is_admin):
        form.fields['facility'].widget = forms.HiddenInput()

    return {
        "title": title,
        "new_user": new_user,
        "form": form,
        "facility": facility,
        "teacher": is_teacher,
    }