Example #1
0
 def do_success_redirect(self, form):
     return redirect_with_message(
         self.request,
         self.get_success_url(form),
         self.get_success_message(form),
         go_back_until=self.go_back_until,
         raw_redirect=self.do_raw_redirect
     )
Example #2
0
 def form_valid(self, form, note_form):
     communication = form.save()
     note_form.save(communication)
     return redirect_with_message(
         self.request,
         self.get_success_url(form, note_form),
         'The communication has been added.',
         go_back_until=['accounts:patient-communications',
                        'accounts:communications'])
Example #3
0
def reset_password_confirm(request, user_id):  # REFACTOR
    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist:  # pragma: no cover
        return HttpResponseNotFound()

    user.get_profile().reset_password()

    return redirect_with_message(request, None,
                                 'The user\'s password has been reset.')
Example #4
0
 def form_valid(self, form: CSVReportForm) -> HttpResponse:
     report = self._get_report()
     redirect_kwargs = {'go_back_until': self.go_back_until}
     if report.should_run_async(form.cleaned_data):
         report.run_async(self.request.user, self._get_post_data())
     else:
         dl = report.create_download(self._get_report_data(form),
                                     self.request.user)
         redirect_kwargs['then_download_id'] = dl.id
     return redirect_with_message(self.request, self.get_success_url(form),
                                  self.get_success_message(form),
                                  **redirect_kwargs)
Example #5
0
def unassign(request, device_id):
    try:
        if request.user.is_professional():
            device = request.user.professional_profile.\
                parent_group.get_devices(group_only=True).get(pk=device_id)
        else:
            device = GDrive.objects.get(pk=device_id)
        assert device.patient is not None
        patient = device.patient
    except (GDrive.DoesNotExist, AssertionError) as e:
        return debug_response(e)

    device.unregister()

    return redirect_with_message(
        request, reverse('gdrives:patient-details', args=[patient.pk]),
        'The device has been unassigned.', ['gdrives:detail'])
Example #6
0
def assign_to_patient(request, device_id, patient_id):
    try:
        if request.user.is_professional():
            patient = request.user.professional_profile.\
                get_patients().get(pk=patient_id)
            device = request.user.professional_profile.\
                parent_group.get_available_devices(patient, True).get(
                    pk=device_id)
        else:
            device = GDrive.objects.get(pk=device_id)
            patient = PatientProfile.myghr_patients.get_users().get(
                pk=patient_id)
    except (GDrive.DoesNotExist, User.DoesNotExist) as e:
        return debug_response(e)

    patient.patient_profile.register_device(device)

    return redirect_with_message(
        request, reverse('gdrives:patient-details', args=[patient.pk]),
        'The device has been assigned.', ['gdrives:detail'])
Example #7
0
def generic_form(request,
                 form_class,
                 page_title='',
                 form_kwargs=None,
                 thanks_view_name=None,
                 redirect_kwargs=None,
                 system_message=None,
                 extra_head_template=None,
                 extra_head_context={},
                 batch=False,
                 batch_variable='batch_ids',
                 only_batch_input=False,
                 batch_queryset=None,
                 redirect_kwargs_from_form_output={},
                 delete_view=None,
                 delete_view_args=[],
                 go_back_until=[],
                 form_template='utils/generic_form.html',
                 extra_form_context={},
                 back_on_error=False,
                 back_on_error_message=None,
                 extra_js=[],
                 form_message=None,
                 send_download_url=None,
                 breadcrumbs=None,
                 extra_delete_warning=None):
    """
    This function basically takes a form object and generates the form page,
    processes the form,
    runs the save method if successful, and then exits in some way specified
    by the parameters.

    Parameters:

    - request: Django request object [required]
    - form_class: The form class that is to be used [required]
    - page_title: The title of the page that will be rendered
    - thanks_view_name: The view name that the form will redirect to upon
    success.  If unspecified
        it will send the user back one page in history.
    - redirect_kwargs: arguments that will be passed to redirect alongside
    thanks_view_name
    - system_message: system_message that will be added to user's session
    and display on next page view
    - extra_head_template: HTML template including extra head content
    - extra_head_context: for rendering extra_head_template
    - batch: specifies if this is a batch form, which requires some slightly
    different processing
    - batch_variable: the POST key that will be used to determine the IDs of
    the batch_variable
    - only_batch_input: need to mark this as true for batch requests that
    don't have any fields except
        for the batch id's
    - batch queryset: set of permissible objects for batch to get
    - redirect_kwargs_from_form_output: this is a dictionary that is
    formatted as redirect_kwarg_key : obj_attribute
        In other words, if the form is going to return a User object and
        you want to redirect to a page like
        /accounts/patients/<patient_id>/ , pass {'patient_id': 'id'} as
        redirect_kwargs_from_form_output
    - delete_view: View name of the delete function for this page.
    - delete_view_args: Used to get URL of above
    - go_back_until: By default, if no thanks_view_name is provided, user will
    be sent back in their history.
        go_back_until should be a list of two-element tuples.  The first
        element should be a view name and
        the second element (optional) should be positional arguments to pass
        to reverse.  By default, it will
        go back three steps, unless one of the parts of the history matches a
        view in go_back_until.  This is
        useful for sending forms back when you don't know how many clicks away
        they should be - e.g. if you have
        a delete form that is exposed directly on the tabular display and one
        that is exposed on edit screen.
    - form_template: template form should be rendered in
    - extra_form_context: for rendering above
    - back_on_error: Send browser back a page if the form has an error
    - back_on_error_message: System message to append for above
    - send_download_url: True/False indicating whether we should ask the form,
     via,
        get_download_id() method, for a download ID to send along with
        redirect.
    - breadcrumbs - Breadcrumb navigation to be rendered
    - extra_delete_warning - Extra notice to be displayed on confirmation
        page
    """

    if form_kwargs is None:
        form_kwargs = {}
    if redirect_kwargs is None:
        redirect_kwargs = {}
    c = extra_form_context.copy()
    if form_message:
        c['form_message'] = form_message
    c['title'] = page_title
    c['extra_js'] = extra_js
    # Do some pre-processing for batch requests
    if batch:
        assert request.method == 'POST', 'batch mode generic_form requests must be sent over POST'  # noqa
        assert isinstance(
            batch_queryset, QuerySet
        ), 'You must specify a batch_queryset if using a batch form.'  # noqa
        post_data = request.POST.copy()
        files_data = request.FILES
        try:
            batch_data = post_data.get(batch_variable)
            post_data.pop(batch_variable)
            form_kwargs['batch'] = list(map(int, batch_data.split(',')))
            form_kwargs['batch_queryset'] = batch_queryset
            c['batch_queryset'] = batch_queryset
        except KeyError:
            raise Exception(
                'generic_form was called in batch mode, but the request did not contain the batch variable (%s)'
                % batch_variable)  # noqa

        c['batch_id_str'] = ','.join(list(map(str, form_kwargs['batch'])))
        if len(post_data) == 1 and post_data.get('csrfmiddlewaretoken'):
            post_data.pop('csrfmiddlewaretoken')
    else:
        post_data = request.POST
        files_data = request.FILES
    if request.method == "POST" and (len(post_data) > 0 or
                                     (batch and only_batch_input)
                                     or len(files_data) > 0):
        form = form_class(post_data, files_data, **form_kwargs)
        if form.is_valid():
            obj = form.save()
            if redirect_kwargs_from_form_output:
                redirect_kwargs = {}
                for k, v in redirect_kwargs_from_form_output.items():
                    redirect_kwargs[k] = getattr(obj, v)
            if send_download_url:
                dl_id = form.get_download_id()
                if dl_id:
                    redirect_kwargs['then_download_id'] = \
                        form.get_download_id()
            if system_message:
                return redirect_with_message(request,
                                             thanks_view_name,
                                             system_message,
                                             go_back_until=go_back_until,
                                             **redirect_kwargs)
            else:
                return genesis_redirect(request,
                                        thanks_view_name,
                                        go_back_until=go_back_until,
                                        **redirect_kwargs)
        else:
            if back_on_error:
                if back_on_error_message:
                    return redirect_with_message(request, None,
                                                 back_on_error_message)
                else:
                    return genesis_redirect(request, None)
    else:
        form = form_class(**form_kwargs)
    c['form'] = form

    if extra_head_template:
        c['extra_head'] = render_to_string(extra_head_template,
                                           extra_head_context)

    if delete_view:
        c['delete_link'] = reverse(delete_view, args=delete_view_args)
    if breadcrumbs is not None:
        c['breadcrumbs'] = breadcrumbs
    if extra_delete_warning is not None:
        c['extra_delete_warning'] = extra_delete_warning

    return render(request, form_template, c)
Example #8
0
def manage_login(request, user_id):  # REFACTOR
    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist as e:  # pragma: no cover
        return debug_response(e)

    form_classes = {
        'change_username': AdminChangeUsernameForm,
        'check_security_question': AdminCheckSecurityQuestionForm,
        'change_password': AdminChangePasswordForm,
        'set_default_password_form': AdminSetDefaultPasswordForm
    }
    forms = {}
    form_kwargs = {'instance': user}

    if request.method == 'POST':
        form_class = form_classes[request.POST['form_name']]
        form = form_class(request.POST, **form_kwargs)
        if form.is_valid():
            form.save()
            form_success_messages = {
                'change_username':
                '******'s username has been updated.',
                'check_security_question':
                'The user\'s security question has '
                'been answered correctly.',
                'change_password':
                '******'s password has been updated.',
                'set_default_password_form':
                'The user\'s password has been updated.'
            }
            message = form_success_messages[request.POST['form_name']]
            return redirect_with_message(
                request,
                None,
                message,
                go_back_until=['accounts:manage-login'])
        forms[request.POST['form_name']] = form
        cj = filter(lambda x: x[1] != form_class, form_classes.items())
        for other_form_name, other_form_class in cj:
            forms[other_form_name] = other_form_class(**form_kwargs)
    else:
        for form_name, form_class in form_classes.items():
            forms[form_name] = form_class(**form_kwargs)
    if user.is_patient():
        group = user.patient_profile.get_group()
        if group:
            breadcrumbs = [
                Breadcrumb('Business Partners',
                           reverse('accounts:manage-groups')),
                Breadcrumb(
                    'Business Partner: {0}'.format(group.name),
                    reverse('accounts:manage-groups-detail', args=[group.pk])),
                Breadcrumb(
                    'Patients'.format(group.name),
                    reverse('accounts:manage-groups-patients',
                            args=[group.pk]))
            ]
        else:
            breadcrumbs = [
                Breadcrumb('Users', reverse('accounts:manage-users'))
            ]
        breadcrumbs.append(
            Breadcrumb(
                'Patient: {0}'.format(user.get_reversed_name()),
                reverse('accounts:manage-patients-detail', args=[user.pk])))
    else:
        group = user.professional_profile.parent_group
        breadcrumbs = [
            Breadcrumb('Business Partners', reverse('accounts:manage-groups')),
            Breadcrumb(
                'Business Partner: {0}'.format(group.name),
                reverse('accounts:manage-groups-detail', args=[group.pk])),
            Breadcrumb(
                'Professionals'.format(group.name),
                reverse('accounts:manage-groups-professionals',
                        args=[group.pk])),
            Breadcrumb(
                'Professional: {0}'.format(user.get_reversed_name()),
                reverse('accounts:manage-professionals-detail',
                        args=[user.pk]))
        ]

    ctx = {
        'target_user': user,
        'forms': forms,
        'breadcrumbs': breadcrumbs,
        'new_password': make_password(user)
    }
    return render(request, 'accounts/manage_login.html', ctx)