django.contrib.messages.error - python examples

Here are the examples of the python api django.contrib.messages.error taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : ubccr
    def test_func(self):
        """ UserPastesTestMixin Tests"""

        if self.request.user.is_superuser:
            return True

        if self.request.user.has_perm('project.can_review_pending_project_reviews'):
            return True

        messages.error(
            self.request, 'You do not have permission to send email for a pending project review.')

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : ubccr
    def test_func(self):
        """ UserPastesTestMixin Tests"""
        if self.request.user.is_superuser:
            return True

        project_obj = get_object_or_404(Project, pk=self.kwargs.get('pk'))

        if project_obj.pi == self.request.user:
            return True

        if project_obj.projectuser_set.filter(user=self.request.user, role__name='Manager', status__name='Active').exists():
            return True

        messages.error(
            self.request, 'You do not have permissions to review this project.')

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : ubccr
    def test_func(self):
        """ UserPastesTestMixin Tests"""
        if self.request.user.is_superuser:
            return True

        project_obj = get_object_or_404(
            Project, pk=self.kwargs.get('project_pk'))

        if project_obj.pi == self.request.user:
            return True

        if project_obj.projectuser_set.filter(user=self.request.user, role__name='Manager', status__name='Active').exists():
            return True

        messages.error(
            self.request, 'You do not have permission to delete publications from this project.')

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def post(self, request, *args, **kwargs):
        if not request.user.has_perm('devapp.change_device'):
            raise PermissionDenied
        try:
            return super().post(request, *args, **kwargs)
        except IntegrityError as e:
            if 'unique constraint' in str(e):
                messages.error(request, _('Duplicate user and port: %s') % e)
            else:
                messages.error(request, e)
        return self.form_invalid(self.get_form())

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : OpenBankProject
    def get_form(self, *args, **kwargs):
        form = super(MyDetailView, self).get_form(*args, **kwargs)
        try:
            form.fields['bank_id'].choices = self.api.get_bank_id_choices()
        except APIError as err:
            messages.error(self.request, err)
        except:
            messages.error(self.request, 'Unknown Error')
        return form

3 View Complete Implementation : views.py
Copyright MIT License
Author : thorrak
@login_required
@site_is_configured
def external_push_brewers_friend_delete(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = BrewersFriendPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "Brewers's Friend push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    message = "Brewers's Friend push target {} has been deleted".format(push_target_id)
    push_target.delete()
    messages.success(request, message)

    return redirect('external_push_list')

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : ubccr
    def test_func(self):
        """ UserPastesTestMixin Tests"""
        if self.request.user.is_superuser:
            return True

        project_obj = get_object_or_404(Project, pk=self.kwargs.get('project_pk'))

        if project_obj.pi == self.request.user:
            return True

        if project_obj.projectuser_set.filter(user=self.request.user, role__name='Manager', status__name='Active').exists():
            return True

        messages.error(self.request, 'You do not have permission to add a new grant to this project.')

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : OpenBankProject
    def get_form(self, *args, **kwargs):
        form = super(CreateView, self).get_form(*args, **kwargs)
        # Cannot add api in constructor: super complains about unknown kwarg
        form.api = self.api
        fields = form.fields
        try:
            fields['bank_id'].choices = self.api.get_bank_id_choices()
        except APIError as err:
            messages.error(self.request, err)
        except:
            messages.error(self.request, "Unknown Error")
        fields['last_ok_date'].initial =\
            datetime.datetime.now().strftime(settings.API_DATETIMEFORMAT)
        return form

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def form_invalid(self, form):
        messages.error(
            self.request,
            _('Form is invalid, check fields and try again')
        )
        return super().form_invalid(form)

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def dispatch(self, request, *args, **kwargs):
        try:
            return super(EditSibscriberMarkers, self).dispatch(
                request, *args, **kwargs
            )
        except ValidationError as e:
            messages.error(request, e)
            return self.render_to_response(self.get_context_data())

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def delete(self, request, *args, **kwargs):
        res = super().delete(request, *args, **kwargs)
        try:
            request.user.log(request.META, 'ddev', 'ip %s, mac: %s, "%s"' % (
                self.object.ip_address or '-',
                self.object.mac_addr or '-',
                self.object.comment or '-'
            ))
            onu_register.delay(
                tuple(dev.pk for dev in Device.objects.exclude(group=None).only('pk').iterator())
            )
        except (DeviceDBException, PermissionError, OperationalError) as e:
            messages.error(request, e)
        messages.success(request, _('Device successfully deleted'))
        return res

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def dispatch(self, request, *args, **kwargs):
        try:
            return super(AbonHomeUpdateView, self).dispatch(
                request, *args,
                **kwargs
            )
        except lib.LogicError as e:
            messages.error(request, e)
        except (NasFailedResult, NasNetworkError) as e:
            messages.error(request, e)
        except lib.MultipleException as errs:
            for err in errs.err_list:
                messages.error(request, err)
        return self.render_to_response(self.get_context_data())

3 View Complete Implementation : views.py
Copyright MIT License
Author : thorrak
@login_required
@site_is_configured
def firmware_flash_flash_status(request, flash_request_id):
    try:
        flash_request = FlashRequest.objects.get(id=flash_request_id)
    except:
        messages.error(request, "Unable to load flash request with ID {}".format(flash_request_id))
        return redirect('firmware_flash_select_family')

    return render(request, template_name='firmware_flash/flash_status.html', context={'flash_request': flash_request,})

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : ubccr
    def test_func(self):
        """ UserPastesTestMixin Tests"""
        if self.request.user.is_superuser:
            return True

        grant_obj = get_object_or_404(Grant, pk=self.kwargs.get('pk'))

        if grant_obj.project.pi == self.request.user:
            return True

        if grant_obj.project.projectuser_set.filter(user=self.request.user, role__name='Manager', status__name='Active').exists():
            return True

        messages.error(self.request, 'You do not have permission to update grant from this project.')

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : ubccr
    def dispatch(self, request, *args, **kwargs):
        project_obj = get_object_or_404(Project, pk=self.kwargs.get('pk'))

        if not project_obj.needs_review:
            messages.error(request, 'You do not need to review this project.')
            return HttpResponseRedirect(reverse('project-detail', kwargs={'pk': project_obj.pk}))

        if 'Auto-Import Project'.lower() in project_obj.satle.lower():
            messages.error(
                request, 'You must update the project satle before reviewing your project. You cannot have "Auto-Import Project" in the satle.')
            return HttpResponseRedirect(reverse('project-update', kwargs={'pk': project_obj.pk}))

        if 'We do not have information about your research. Please provide a detailed description of your work and update your field of science. Thank you!' in project_obj.description:
            messages.error(
                request, 'You must update the project description before reviewing your project.')
            return HttpResponseRedirect(reverse('project-update', kwargs={'pk': project_obj.pk}))

        return super().dispatch(request, *args, **kwargs)

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : ubccr
    def test_func(self):
        """ UserPastesTestMixin Tests"""

        if self.request.user.is_superuser:
            return True

        if self.request.user.has_perm('project.can_review_pending_project_reviews'):
            return True

        messages.error(
            self.request, 'You do not have permission to review pending project reviews.')

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : ubccr
    def dispatch(self, request, *args, **kwargs):
        if request.user.is_superuser:
            messages.error(request, 'You are already a super user')
            return HttpResponseRedirect(reverse('user-profile'))

        if request.user.userprofile.is_pi:
            messages.error(request, 'Your account has already been upgraded')
            return HttpResponseRedirect(reverse('user-profile'))

        return super().dispatch(request, *args, **kwargs)

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : ubccr
    def test_func(self):
        """ UserPastesTestMixin Tests"""
        if self.request.user.is_superuser:
            return True

        if self.request.user.has_perm('project.can_view_all_projects'):
            return True

        project_obj = self.get_object()

        if project_obj.projectuser_set.filter(user=self.request.user, status__name='Active').exists():
            return True

        messages.error(
            self.request, 'You do not have permission to view the previous page.')
        return False

3 View Complete Implementation : context_processors.py
Copyright GNU Affero General Public License v3.0
Author : OpenBankProject
def api_user_id(request):
    """Returns the API user id of the logged-in user"""
    user_id = 'not authenticated'
    if request.user.is_authenticated:
        try:
            api = API(request.session.get('obp'))
            data = api.get('/users/current')
            user_id = data['user_id']
        except APIError as err:
            messages.error(request, err)
        except Exception as err:
            messages.error(request, err)
    return {'API_USER_ID': user_id}

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def delete(self, request, *args, **kwargs):
        group_id = self.kwargs.get('group_id')
        group_with_subscribers = models.Group.objects.annotate(
            subscribers_count=Count('abon')
        ).filter(subscribers_count__gt=0, pk=group_id).first()
        if group_with_subscribers is not None:
            messages.error(request, _('Group is contain subscribers. Remove them before delete group'))
            return HttpResponseRedirect(self.success_url)
        return super().delete(request, *args, **kwargs)

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : OpenBankProject
    def get_context_data(self, **kwargs):
        context = super(MyDetailView, self).get_context_data(**kwargs)
        # NOTE: astuming there is just one user with that email address
        # The API needs a call 'get user by id'!
        user = {}
        try:
            urlpath = '/users/current'
            user = self.api.get(urlpath)
            context['form'].fields['user_id'].initial = user['user_id']
        except APIError as err:
            messages.error(self.request, err)
        except Exception as err:
            messages.error(self.request, 'Unknown Error')

        context.update({
            'apiuser': user,  # 'user' is logged-in user in template context
        })
        return context

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : OpenBankProject
    def get_form(self, *args, **kwargs):
        form = super(DetailView, self).get_form(*args, **kwargs)
        try:
            form.fields['bank_id'].choices = self.api.get_bank_id_choices()
        except APIError as err:
            messages.error(self.request, err)
        except:
            messages.error(self.request, 'Unknown Error')
        return form

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : ubccr
    def test_func(self):
        """ UserPastesTestMixin Tests"""
        if self.request.user.is_superuser:
            return True

        project_obj = get_object_or_404(Project, pk=self.kwargs.get('project_pk'))

        if project_obj.pi == self.request.user:
            return True

        if project_obj.projectuser_set.filter(user=self.request.user, role__name='Manager', status__name='Active').exists():
            return True

        messages.error(self.request, 'You do not have permission to delete grants from this project.')

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def dispatch(self, request, *args, **kwargs):
        try:
            return super(IpUpdateView, self).dispatch(request, *args, **kwargs)
        except lib.LogicError as e:
            messages.error(request, e)
        except IntegrityError as e:
            str_text = str(e)
            if 'abonent_ip_address_nas_id' in str_text and 'duplicate key value' in str_text:
                messages.error(request, _('IP address conflict'))
            else:
                messages.error(request, e)
        return self.render_to_response(self.get_context_data(**kwargs))

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : OpenBankProject
    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        api = API(self.request.session.get('obp'))
        try:
            urlpath = '/config'
            config = api.get(urlpath)
        except APIError as err:
            messages.error(self.request, err)
            config = {}
        except:
            messages.error(self.request, "Unknown Error")
            config = {}

        context.update({
            'config_json': json.dumps(config, indent=4),
        })
        return context

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def get(self, request, *args, **kwargs):
        r = super().get(request, *args, **kwargs)
        abon = self.object
        if abon.nas is None:
            messages.error(self.request, _('gateway required'))
            return redirect(
                'abonapp:abon_home',
                gid=self.kwargs.get('gid'),
                uname=self.kwargs.get('uname')
            )
        return r

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def form_valid(self, form):
        r = super(IpUpdateView, self).form_valid(form)
        abon = self.object
        try:
            customer_nas_command.delay(abon.pk, 'sync')
        except OperationalError as e:
            messages.error(self.request, str(e))
        else:
            messages.success(self.request, _('Ip successfully updated'))
        return r

3 View Complete Implementation : views.py
Copyright MIT License
Author : thorrak
@login_required
@site_is_configured
def external_push_delete(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = GenericPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "External push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    message = 'Push target {} has been deleted'.format(push_target.name)
    push_target.delete()
    messages.success(request, message)

    return redirect('external_push_list')

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
@login_required
@only_admins
def to_single_dev(request):
    dot_id = safe_int(request.GET.get('dot_id'))
    if dot_id <= 0:
        return HttpResponseBadRequest
    dev = Device.objects.filter(dot__id=dot_id).first()
    if dev is None:
        messages.error(request, gettext('Devices is not found on the dot'))
        return redirect('mapapp:edit_dot', dot_id)
    grp_id = dev.group.pk
    return redirect('devapp:view', grp_id, dev.pk)

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : ubccr
    def test_func(self):
        """ UserPastesTestMixin Tests"""

        if self.request.user.is_superuser:
            return True

        if self.request.user.has_perm('project.can_review_pending_project_reviews'):
            return True

        messages.error(
            self.request, 'You do not have permission to mark a pending project review as completed.')

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def form_valid(self, form):
        r = super(AbonHomeUpdateView, self).form_valid(form)
        abon = self.object
        try:
            customer_nas_command.delay(abon.pk, 'sync')
        except OperationalError as e:
            messages.error(self.request, str(e))
        else:
            messages.success(self.request, _('edit abon success msg'))
        return r

3 View Complete Implementation : views.py
Copyright MIT License
Author : thorrak
@login_required
@site_is_configured
def external_push_brewfather_delete(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = BrewfatherPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "Brewfather push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    message = "Brewfather push target {} has been deleted".format(push_target_id)
    push_target.delete()
    messages.success(request, message)

    return redirect('external_push_list')

3 View Complete Implementation : context_processors.py
Copyright GNU Affero General Public License v3.0
Author : OpenBankProject
def api_username(request):
    """Returns the API username of the logged-in user"""
    username = 'not authenticated'
    if request.user.is_authenticated:
        try:
            api = API(request.session.get('obp'))
            data = api.get('/users/current')
            username = data['username']
        except APIError as err:
            messages.error(request, err)
        except Exception as err:
            messages.error(request, err)
    return {'API_USERNAME': username}

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : OpenBankProject
    def get_banks(self):
        api = API(self.request.session.get('obp'))
        try:
            urlpath = '/banks'
            result = api.get(urlpath)
            if 'banks' in result:
                return [bank['id'] for bank in result['banks']]
            else:
                return []
        except APIError as err:
            messages.error(self.request, err)
            return []

3 View Complete Implementation : connections.py
Copyright MIT License
Author : abelardopardo
def toggle(
    request: HttpRequest,
    conn: models.Connection,
    toggle_url: str,
) -> JsonResponse:
    """Toggle the enable field in the given connection."""
    if not conn:
        messages.error(
            request,
            _('Incorrect invocation of toggle question change function.'))
        return JsonResponse({}, status=404)

    conn.enabled = not conn.enabled
    conn.save()
    conn.log(request.user, conn.toggle_event, enabled=conn.enabled)
    return JsonResponse({'is_checked': conn.enabled, 'toggle_url': toggle_url})

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
@login_required
@only_admins
def task_failed(request, task_id):
    try:
        task = get_object_or_404(Task, id=task_id)
        task.do_fail(request.user)
        task.send_notification()
    except TaskException as e:
        messages.error(request, e)
    return redirect('taskapp:home')

0 View Complete Implementation : run.py
Copyright MIT License
Author : abelardopardo
@user_pastes_test(is_instructor)
@get_action(pf_related='actions')
def run_action(
    request: http.HttpRequest,
    pk: int,
    workflow: Optional[models.Workflow] = None,
    action: Optional[models.Action] = None,
) -> http.HttpResponse:
    """Run specific run action view depending on action type.

    If it is a Survey or todo, renders a table with all rows that
    satisfy the filter condition and includes a link to enter data for each
    of them.

    :param request: HttpRequest
    :param pk: Action id. It is astumed to be an action In
    :param workflow: Workflow object to be astigned by the decorators
    :param action: Action object to be astigned by the decorators
    :return: HttpResponse
    """
    del pk, workflow
    if not celery_is_up():
        messages.error(
            request,
            _('Unable to execute actions due to a misconfiguration. '
              + 'Ask your system administrator to enable message queueing.'))
        return redirect(reverse('action:index'))

    return services.ACTION_PROCESS_FACTORY.process_run_request(
        action.action_type,
        request=request,
        action=action,
        prev_url=reverse('action:run', kwargs={'pk': action.id}))

0 View Complete Implementation : crud.py
Copyright MIT License
Author : abelardopardo
@user_pastes_test(is_instructor)
@get_workflow()
def finish_scheduling(
    request: http.HttpRequest,
    workflow: Optional[models.Workflow] = None,
) -> http.HttpResponse:
    """Finish the create/edit operation of a scheduled operation."""
    del workflow
    payload = SessionPayload(request.session)
    if payload is None:
        # Something is wrong with this execution. Return to action table.
        messages.error(
            request,
            _('Incorrect action scheduling invocation.'))
        return redirect('action:index')

    return services.schedule_crud_factory.crud_finish(
        payload.get('operation_type'),
        request=request,
        payload=payload)

0 View Complete Implementation : workflow_crud.py
Copyright MIT License
Author : abelardopardo
@user_pastes_test(is_instructor)
@ajax_required
@get_workflow()
def update(
    request: http.HttpRequest,
    wid: Optional[int] = None,
    workflow: Optional[models.Workflow] = None,
) -> http.JsonResponse:
    """Update the workflow information (name, description).

    :param request: Request object
    :param wid: Workflow ID
    :param workflow: workflow being manipulated.
    :return: JSON response
    """
    if workflow.user != request.user:
        # If the user does not own the workflow, notify error and go back to
        # index
        messages.error(
            request,
            _('You can only rename workflows you created.'))
        return http.JsonResponse({'html_redirect': ''})

    form = forms.WorkflowForm(
        request.POST or None,
        instance=workflow,
        workflow_user=workflow.user)

    if request.method == 'POST' and form.is_valid():
        if not form.has_changed():
            return http.JsonResponse({'html_redirect': None})

        return services.save_workflow_form(request, form)

    return http.JsonResponse({
        'html_form': render_to_string(
            'workflow/includes/partial_workflow_update.html',
            {'form': form},
            request=request),
    })

0 View Complete Implementation : survey.py
Copyright MIT License
Author : abelardopardo
    def process_edit_request(
        self,
        request: http.HttpRequest,
        workflow: models.Workflow,
        action: models.Action
    ) -> http.HttpResponse:
        """Process the action edit request.

        :param request: Http Request received
        :param workflow: Workflow being manipulated
        :param action: Action being used as a survey
        :return: Http response with the right edit template.
        """

        context = self.get_render_context(action)
        try:
            self.extend_edit_context(workflow, action, context)
        except Exception as exc:
            messages.error(request, str(exc))
            return redirect(reverse('action:index'))

        return render(request, self.edit_template, context)

0 View Complete Implementation : workflow_crud.py
Copyright MIT License
Author : abelardopardo
@user_pastes_test(is_instructor)
def index(request: http.HttpRequest) -> http.HttpResponse:
    """Render the page with the list of workflows.

    :param request: HttpRequest received
    :return: Response with the index page rendered
    """
    remove_workflow_from_session(request)

    # Report if Celery is not running properly
    if request.user.is_superuser:
        # Verify that celery is running!
        if not celery_is_up():
            messages.error(
                request,
                _(
                    'WARNING: Celery is not currently running. '
                    + 'Please configure it correctly.',
                ),
            )

    return render(
        request,
        'workflow/index.html',
        services.get_index_context(request.user))

0 View Complete Implementation : views.py
Copyright MIT License
Author : abelardopardo
@user_pastes_test(is_instructor)
@get_workflow()
def view(
    request: http.HttpRequest,
    pk: int,
    workflow: Optional[models.Workflow] = None,
) -> http.HttpResponse:
    """View the content of one of the logs.

    :param request: Http Request received
    :param pk: Primary key of the log to view
    :param workflow: Workflow being manipulated (set by the decorators)
    :return: Http response rendering the view.html
    """
    # Get the log item
    log_item = workflow.logs.filter(pk=pk, user=request.user).first()

    # If the log item is not there, flag!
    if not log_item:
        messages.error(request, _('Incorrect log number requested'))
        return redirect(reverse('logs:index'))

    return render(
        request,
        'logs/view.html',
        {
            'log_item': log_item,
            'json_pretty': json.dumps(
                log_item.payload,
                sort_keys=True,
                indent=4)})

0 View Complete Implementation : table_view.py
Copyright MIT License
Author : abelardopardo
@user_pastes_test(is_instructor)
@ajax_required
@get_workflow(pf_related='columns')
def view_add(
    request: HttpRequest,
    workflow: Optional[models.Workflow] = None,
) -> JsonResponse:
    """Create a new view.

    :param request: Request object
    :param workflow: Workflow being processed
    :return: AJAX response
    """
    # Get the workflow element
    if workflow.nrows == 0:
        messages.error(
            request,
            _('Cannot add a view to a workflow without data'))
        return JsonResponse({'html_redirect': ''})

    # Form to read/process data
    form = forms.ViewAddForm(request.POST or None, workflow=workflow)

    if request.method == 'POST' and form.is_valid():
        if not form.has_changed():
            return JsonResponse({'html_redirect': None})

        view = form.save(commit=False)
        services.save_view_form(request.user, workflow, view)
        form.save_m2m()  # Needed to propagate the save effect to M2M relations

        return JsonResponse({'html_redirect': ''})

    return JsonResponse({
        'html_form': render_to_string(
            'table/includes/partial_view_add.html',
            {'form': form, 'id': form.instance.id},
            request=request),
    })

0 View Complete Implementation : criterion_crud.py
Copyright MIT License
Author : abelardopardo
@user_pastes_test(is_instructor)
@ajax_required
@get_workflow(pf_related=['columns'])
def criterion_remove(
    request: http.HttpRequest,
    pk: int,
    workflow: Optional[models.Workflow] = None,
) -> http.JsonResponse:
    """Remove the criterion from the rubric. Does not remove the column.

    :param request:
    :param pk: For the Action/Column/condition triplet
    :param workflow: workflow being manipulated (set by the decorator)
    :return: JSON Response
    """
    del workflow
    triplet = models.ActionColumnConditionTuple.objects.filter(pk=pk).first()
    if not triplet:
        messages.error(
            request,
            _('Incorrect invocation of criterion delete function'),
        )
        return http.JsonResponse({'html_redirect': ''})

    if request.method == 'POST':
        triplet.log(request.user, models.Log.ACTION_RUBRIC_CRITERION_DELETE)
        triplet.delete()
        return http.JsonResponse({'html_redirect': ''})

    return http.JsonResponse({
        'html_form': render_to_string(
            'workflow/includes/partial_criterion_remove.html',
            {'pk': pk, 'cname': triplet.column.name},
            request=request)})

0 View Complete Implementation : run.py
Copyright MIT License
Author : abelardopardo
@user_pastes_test(is_instructor)
@get_workflow()
def run_done(
    request: http.HttpRequest,
    workflow: Optional[models.Workflow] = None,
) -> http.HttpResponse:
    """Finish the create/edit operation of a scheduled operation."""
    payload = SessionPayload(request.session)
    if payload is None:
        # Something is wrong with this execution. Return to action table.
        messages.error(
            request,
            _('Incorrect action run invocation.'))
        return redirect('action:index')

    return services.ACTION_PROCESS_FACTORY.process_run_request_done(
        payload.get('operation_type'),
        request=request,
        workflow=workflow,
        payload=payload)

0 View Complete Implementation : column_crud.py
Copyright MIT License
Author : abelardopardo
@user_pastes_test(is_instructor)
@ajax_required
@get_column(pf_related='columns')
def column_clone(
    request: HttpRequest,
    pk: int,
    workflow: Optional[models.Workflow] = None,
    column: Optional[models.Column] = None,
) -> JsonResponse:
    """Clone a column in the table attached to a workflow.

    :param request: HTTP request
    :param pk: ID of the column to clone.
    :param workflow: Workflow being processed
    :param column: Column to clone (set by the decorator)
    :return: Render the clone column form
    """
    del workflow
    # Get the name of the column to clone
    context = {'pk': pk, 'cname': column.name}

    if request.method == 'GET':
        return JsonResponse({
            'html_form': render_to_string(
                'workflow/includes/partial_column_clone.html',
                context,
                request=request),
        })

    # Proceed to clone the column
    try:
        services.clone_column(request.user, column)
    except Exception as exc:
        messages.error(
            request,
            _('Unable to clone column: {0}').format(str(exc)))
        return JsonResponse({'html_redirect': ''})

    return JsonResponse({'html_redirect': ''})

0 View Complete Implementation : decorators.py
Copyright MIT License
Author : abelardopardo
def _get_requested_workflow(
    request: http.HttpRequest,
    wid: int = None,
    s_related: object = None,
    pf_related: object = None,
) -> Optional[models.Workflow]:
    """Access the requested workflow.

    :param request: HTTP request received
    :param s_related: select_related to use when fetching the workflow
    :param pf_related: prefetch_related to use when fetching the workflow
    :param wid: ID of the requested workflow
    :return
    """
    try:
        workflow = acquire_workflow_access(
            request.user,
            request.session,
            wid=wid,
            select_related=s_related,
            prefetch_related=pf_related)
    except Exception as exc:
        messages.error(request, str(exc))
        workflow = None

    return workflow

0 View Complete Implementation : views.py
Copyright MIT License
Author : abelardopardo
    def post(self, request, *args, **kwargs):
        del args, kwargs
        user = self.request.user
        user_form = forms.UserForm(request.POST, instance=user)
        profile_form = forms.ProfileForm(request.POST,
                                         request.FILES,
                                         instance=user.profile)
        if not (user_form.is_valid() and profile_form.is_valid()):
            messages.error(request,
                           _("There was a problem with the form. "
                             "Please check the details."))
            user_form = forms.UserForm(instance=user)
            profile_form = forms.ProfileForm(instance=user.profile)
            return super().get(request,
                               user_form=user_form,
                               profile_form=profile_form)
        # Both forms are fine. Time to save!
        user_form.save()
        profile = profile_form.save(commit=False)
        profile.user = user
        profile.save()
        messages.success(request, _("Profile details saved!"))
        return redirect("profiles:show_self")

0 View Complete Implementation : views.py
Copyright MIT License
Author : abelardopardo
@user_pastes_test(is_instructor)
def callback(request: WSGIRequest) -> http.HttpResponse:
    """Process the call received from the server.

    This is supposed to contain the token so it is saved to the database and
    then redirects to a page previously stored in the session object.

    :param request: Request object
    :return: Redirection to the stored page
    """
    payload = SessionPayload(request.session)

    # If there is no payload, something went wrong.
    if payload is None:
        # Something is wrong with this execution. Return to action table.
        messages.error(
            request,
            _('Incorrect Canvas callback invocation.'))
        return redirect('action:index')

    # Check first if there has been some error
    error_string = request.GET.get('error')
    if error_string:
        messages.error(
            request,
            ugettext('Error in OAuth2 step 1 ({0})').format(error_string))
        return redirect('action:index')

    status = services.process_callback(request, payload)
    if status:
        messages.error(request, status)
        return redirect('action:index')

    return redirect(
        request.session.get(services.return_url_key, reverse('action:index')))

0 View Complete Implementation : __init__.py
Copyright MIT License
Author : abelardopardo
    def message_to_error(self, request):
        """Store the message as error in the given request."""
        messages.error(request, self.message)