Python django.contrib.messages.ERROR Examples

The following are 30 code examples of django.contrib.messages.ERROR(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.messages , or try the search function .
Example #1
Source File: save_search.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def save_search(request):
    current_user = Person.objects.get(userid=request.user.username)
    saveform = SaveSearchForm(request.POST)
    
    if saveform.is_valid():
        name = saveform.cleaned_data['name']
        existing_ss = SavedSearch.objects.filter(person=saveform.data['person'])
        existing_ss = [ss for ss in existing_ss if ss.name()==name]
        for ss in existing_ss:
            ss.delete()
        
        ss = saveform.save(commit=False)
        ss.person = current_user
        ss.save()
        messages.add_message(request, messages.SUCCESS, 'Search Saved as "%s".' % (name))
        return HttpResponseRedirect(reverse('grad:index'))
    else:
        messages.add_message(request, messages.ERROR, saveform.errors.as_text())
        if True or 'query' in saveform.data:
            return HttpResponseRedirect(reverse('grad:search') + '?' + saveform.data['query'])
        else:
            return HttpResponseRedirect(reverse('grad:search')) 
Example #2
Source File: decorators.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
def data_figure_file(func):
    """ This decorator checks that a file is a data or figure file in the specified article

    :param func: the function to callback from the decorator
    :return: either the function call or raises an Http404
    """

    def wrapper(request, *args, **kwargs):
        file_object = get_object_or_404(core_models.File, pk=kwargs['file_id'])

        try:
            article = models.Article.get_article(request.journal, 'id', kwargs['article_id'])
        except KeyError:
            article = models.Article.get_article(request.journal, kwargs['identifier_type'], kwargs['identifier'])

        if is_data_figure_file(file_object, article):
            return func(request, *args, **kwargs)

        messages.add_message(request, messages.ERROR, 'File is not a data or figure file.')
        deny_access(request)

    return wrapper


# General checks to avoid "raise Http404()" logic elsewhere 
Example #3
Source File: decorators.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
def file_edit_user_required(func):
    """ This decorator checks permissions for a user to edit a specific article

    :param func: the function to callback from the decorator
    :return: either the function call or raises an Http404
    """

    def wrapper(request, *args, **kwargs):
        file_object = get_object_or_404(core_models.File, pk=kwargs['file_id'])

        try:
            article = models.Article.get_article(request.journal, 'id', kwargs['article_id'])
        except KeyError:
            article = models.Article.get_article(request.journal, kwargs['identifier_type'], kwargs['identifier'])

        if can_edit_file(request, request.user, file_object, article):
            return func(request, *args, **kwargs)

        messages.add_message(request, messages.ERROR, 'File editing not accessible to this user.')
        deny_access(request)

    return wrapper 
Example #4
Source File: decorators.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
def file_history_user_required(func):
    """ This decorator checks permissions for a user to view the history of a specific article

    :param func: the function to callback from the decorator
    :return: either the function call or raises an Http404
    """

    def wrapper(request, *args, **kwargs):
        file_object = get_object_or_404(core_models.File, pk=kwargs['file_id'])

        try:
            article = models.Article.get_article(request.journal, 'id', kwargs['article_id'])
        except KeyError:
            article = models.Article.get_article(request.journal, kwargs['identifier_type'], kwargs['identifier'])

        if can_view_file_history(request, request.user, file_object, article):
            return func(request, *args, **kwargs)

        messages.add_message(request, messages.ERROR, 'File editing not accessible to this user.')
        deny_access(request)

    return wrapper 
Example #5
Source File: decorators.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
def file_user_required(func):
    """ This decorator checks that a user has permission to view a file

    :param func: the function to callback from the decorator
    :return: either the function call or raises an Http404
    """

    def wrapper(request, *args, **kwargs):
        file_id = kwargs['file_id']

        if file_id == "None":
            return func(request, *args, **kwargs)

        file_object = get_object_or_404(core_models.File, pk=file_id)

        if can_view_file(request, request.user, file_object):
            return func(request, *args, **kwargs)
        else:
            messages.add_message(request, messages.ERROR, 'File is not accessible to this user.')
            deny_access(request)

    return wrapper 
Example #6
Source File: prize.py    From donation-tracker with Apache License 2.0 6 votes vote down vote up
def draw_prize_internal(self, request, queryset, limit):
        numDrawn = 0
        for prize in queryset:
            if prize.key_code:
                drawn, msg = prizeutil.draw_keys(prize)
                if drawn:
                    numDrawn += len(msg['winners'])
                else:
                    messages.error(request, msg['error'])
            else:
                if limit is None:
                    limit = prize.maxwinners
                numToDraw = min(limit, prize.maxwinners - prize.current_win_count())
                drawingError = False
                while not drawingError and numDrawn < numToDraw:
                    drawn, msg = prizeutil.draw_prize(prize)
                    if not drawn:
                        self.message_user(request, msg['error'], level=messages.ERROR)
                        drawingError = True
                    else:
                        numDrawn += 1
        if numDrawn > 0:
            self.message_user(request, '%d prizes drawn.' % numDrawn) 
Example #7
Source File: forms.py    From conf_site with MIT License 6 votes vote down vote up
def _build_days(self, data):
        "Get or Create Days based on schedule type and set of Days"
        created_days = []
        days = set([x[self.DATE_KEY] for x in data])
        for day in days:
            try:
                date = datetime.strptime(day, "%m/%d/%Y")
            except ValueError:
                [x.delete() for x in created_days]
                return messages.ERROR, "Malformed data found: %s." % day
            day, created = Day.objects.get_or_create(
                schedule=self.schedule, date=date
            )
            if created:
                created_days.append(day)
        return created_days 
Example #8
Source File: submission.py    From online-judge with GNU Affero General Public License v3.0 6 votes vote down vote up
def judge(self, request, queryset):
        if not request.user.has_perm('judge.rejudge_submission') or not request.user.has_perm('judge.edit_own_problem'):
            self.message_user(request, gettext('You do not have the permission to rejudge submissions.'),
                              level=messages.ERROR)
            return
        queryset = queryset.order_by('id')
        if not request.user.has_perm('judge.rejudge_submission_lot') and \
                queryset.count() > settings.DMOJ_SUBMISSIONS_REJUDGE_LIMIT:
            self.message_user(request, gettext('You do not have the permission to rejudge THAT many submissions.'),
                              level=messages.ERROR)
            return
        if not request.user.has_perm('judge.edit_all_problem'):
            id = request.profile.id
            queryset = queryset.filter(Q(problem__authors__id=id) | Q(problem__curators__id=id))
        judged = len(queryset)
        for model in queryset:
            model.judge(rejudge=True, batch_rejudge=True)
        self.message_user(request, ungettext('%d submission was successfully scheduled for rejudging.',
                                             '%d submissions were successfully scheduled for rejudging.',
                                             judged) % judged) 
Example #9
Source File: admin.py    From mangaki with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle_merge_errors(response, request, final_work, nb_merged,
                        message_user):
    if response == MergeErrors.NO_ID:
        message_user(request,
                     "Aucun ID n'a été fourni pour la fusion.",
                     level=messages.ERROR)
    if response == MergeErrors.FIELDS_MISSING:
        message_user(request,
                     """Un ou plusieurs des champs requis n'ont pas été remplis.
                          (Détails: {})""".format(", ".join(final_work)),
                     level=messages.ERROR)
    if response == MergeErrors.NOT_ENOUGH_WORKS:
        message_user(request,
                     "Veuillez sélectionner au moins 2 œuvres à fusionner.",
                     level=messages.WARNING)
    if response is None:  # Confirmed
        message_user(request,
                     format_html('La fusion de {:d} œuvres vers <a href="{:s}">{:s}</a> a bien été effectuée.'
                                 .format(nb_merged, final_work.get_absolute_url(), final_work.title))) 
Example #10
Source File: default.py    From cadasta-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
def form_valid(self, form):
        login = form.cleaned_data['login']
        user = form.user

        if (login == user.username and
                not user.phone_verified and
                not user.email_verified):
            user.is_active = False
            user.save()
            messages.add_message(
                self.request, messages.ERROR, account_inactive)
            return redirect(reverse_lazy('account:resend_token'))

        if(login == user.email and not user.email_verified or
                login == user.phone and not user.phone_verified):
            messages.add_message(
                self.request, messages.ERROR, unverified_identifier)
            return redirect(reverse_lazy('account:resend_token'))
        else:
            return super().form_valid(form) 
Example #11
Source File: default.py    From cadasta-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_form_kwargs(self, *args, **kwargs):
        form_kwargs = super().get_form_kwargs(*args, **kwargs)
        try:
            user_id = self.request.session['password_reset_id']
            user = User.objects.get(id=user_id)
            form_kwargs['user'] = user
        except KeyError:
            message = _(
                "You must first verify your token before resetting password."
                " Click <a href='{url}'>here</a> to get the password reset"
                " verification token. ")
            message = format_html(message.format(
                url=reverse_lazy('account:account_reset_password')))
            messages.add_message(self.request, messages.ERROR, message)

        return form_kwargs 
Example #12
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def version_delete(request: HttpRequest, course_slug: str, activity_slug: str, question_id: str, version_id: str) -> HttpResponse:
    if request.method in ['POST', 'DELETE']:
        quiz = get_object_or_404(Quiz, activity__slug=activity_slug, activity__offering__slug=course_slug)
        if quiz.completed():
            return ForbiddenResponse(request, 'Quiz is completed. You cannot modify questions after the end of the quiz time')
        question = get_object_or_404(Question, quiz=quiz, id=question_id)
        version = get_object_or_404(QuestionVersion, question=question, id=version_id)
        other_versions = QuestionVersion.objects.filter(question=question).exclude(id=version_id)
        if not other_versions.exists():
            messages.add_message(request, messages.ERROR, 'Cannot delete the only version of a question.')
            return redirect('offering:quiz:question_edit', course_slug=course_slug, activity_slug=activity_slug, question_id=question_id, version_id=version_id)
        version.status = 'D'
        version.save()
        messages.add_message(request, messages.SUCCESS, 'Question version deleted.')
        LogEntry(userid=request.user.username, description='deleted quiz question version id=%i' % (question.id,),
                 related_object=question).save()
        return redirect('offering:quiz:index', course_slug=course_slug, activity_slug=activity_slug)
    else:
        return HttpError(request, status=405, title="Method Not Allowed", error='POST or DELETE requests only.') 
Example #13
Source File: admin.py    From django-freeradius with GNU General Public License v3.0 6 votes vote down vote up
def delete_selected_groups(self, request, queryset):
        if self.get_default_queryset(request, queryset).exists():
            msg = _('Cannot proceed with the delete operation because '
                    'the batch of items contains the default group, '
                    'which cannot be deleted')
            self.message_user(request, msg, messages.ERROR)
            return False
        if not self.has_delete_permission(request):
            raise PermissionDenied
        n = queryset.count()
        if n:
            queryset.delete()
            self.message_user(request, _("Successfully deleted %(count)d %(items)s.") % {
                "count": n, "items": model_ngettext(self.opts, n)
            }, messages.SUCCESS)
        return None 
Example #14
Source File: views.py    From superbook with MIT License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        if 'sign_in' in request.POST:
            form = self.signin_form_class(**self.get_form_kwargs())
            if not form.is_valid():
                messages.add_message(request,
                                     messages.ERROR,
                                     "Unable login! "
                                     "Check username/password")
                return super().get(request,
                                   signup_form=self.signup_form_class(),
                                   signin_form=form)
            username = form.cleaned_data["username"]
            password = form.cleaned_data["password"]
            user = authenticate(username=username, password=password)
            if user is not None and user.is_active:
                login(self.request, user)
            else:
                messages.add_message(request, messages.ERROR,
                                     "Unable to find given username!")
        if 'sign_up' in request.POST:
            form = self.signup_form_class(**self.get_form_kwargs())
            if not form.is_valid():
                messages.add_message(request,
                                     messages.ERROR,
                                     "Unable to register! "
                                     "Please retype the details")
                return super().get(request,
                                   signin_form=self.signin_form_class(),
                                   signup_form=form)
            form.save()
            username = form.cleaned_data["username"]
            password = form.cleaned_data["password1"]
            messages.add_message(request,
                                 messages.INFO,
                                 "{0} added sucessfully".format(
                                     username))
            # Login automatically
            user = authenticate(username=username, password=password)
            login(self.request, user)
        return redirect("home") 
Example #15
Source File: views.py    From ideascube with GNU Affero General Public License v3.0 5 votes vote down vote up
def form_invalid(self, form):
        msg = _('Specimen {specimen} not found or already done.')
        msg = msg.format(specimen=form.data['specimen'])
        messages.add_message(self.request, messages.ERROR, msg)
        return self.redirect(form) 
Example #16
Source File: views.py    From ideascube with GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        context = {}
        if 'do_loan' in request.POST:
            loan_form = LoanForm(data=request.POST)
            if loan_form.is_valid():
                specimen = loan_form.cleaned_data['specimen']
                user = loan_form.cleaned_data['user']
                Loan.objects.create(
                    specimen=specimen,
                    user=user,
                    comments=loan_form.cleaned_data['comments'],
                    due_date=loan_form.cleaned_data['due_date'],
                    by=request.user)
                msg = _('Item {item} has been loaned to {user}')
                msg = msg.format(item=specimen.item, user=user)
                messages.add_message(self.request, messages.SUCCESS, msg)
            else:
                context['loan_form'] = loan_form
        elif 'do_return' in request.POST:
            return_form = ReturnForm(data=request.POST)
            if return_form.is_valid():
                loan = return_form.cleaned_data['loan']
                if loan:
                    loan.mark_returned()
                    msg = _('Item {item} has been returned')
                    msg = msg.format(item=loan.specimen.item)
                    status = messages.SUCCESS
                else:
                    msg = _('Item not found')
                    status = messages.ERROR
                messages.add_message(self.request, status, msg)
            else:
                context['return_form'] = return_form
        return self.render_to_response(self.get_context_data(**context)) 
Example #17
Source File: views.py    From ideascube with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, *args, **kwargs):
        self.form = ExportLoanForm(self.request.GET)
        if self.form.is_valid():
            return super().get(*args, **kwargs)
        else:
            msg = _('Error while processing loans export')
            messages.add_message(self.request, messages.ERROR, msg)
            messages.add_message()
            return HttpResponseRedirect(reverse_lazy('monitoring:loan')) 
Example #18
Source File: default.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def delete(self, *args, **kwargs):
        if self.admin_is_deleting_themselves():
            messages.add_message(self.request, messages.ERROR,
                                 _("Administrators cannot remove themselves."))
            return redirect('organization:members_edit', **self.kwargs)
        return super().delete(*args, **kwargs) 
Example #19
Source File: submission.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def recalculate_score(self, request, queryset):
        if not request.user.has_perm('judge.rejudge_submission'):
            self.message_user(request, gettext('You do not have the permission to rejudge submissions.'),
                              level=messages.ERROR)
            return
        submissions = list(queryset.defer(None).select_related(None).select_related('problem')
                           .only('points', 'case_points', 'case_total', 'problem__partial', 'problem__points'))
        for submission in submissions:
            submission.points = round(submission.case_points / submission.case_total * submission.problem.points
                                      if submission.case_total else 0, 1)
            if not submission.problem.partial and submission.points < submission.problem.points:
                submission.points = 0
            submission.save()
            submission.update_contest()

        for profile in Profile.objects.filter(id__in=queryset.values_list('user_id', flat=True).distinct()):
            profile.calculate_points()
            cache.delete('user_complete:%d' % profile.id)
            cache.delete('user_attempted:%d' % profile.id)

        for participation in ContestParticipation.objects.filter(
                id__in=queryset.values_list('contest__participation_id')).prefetch_related('contest'):
            participation.recompute_results()

        self.message_user(request, ungettext('%d submission were successfully rescored.',
                                             '%d submissions were successfully rescored.',
                                             len(submissions)) % len(submissions)) 
Example #20
Source File: default.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def form_invalid(self, form):
        messages.add_message(self.request, messages.ERROR,
                             _("Failed to update profile information"))
        return super().form_invalid(form) 
Example #21
Source File: admin.py    From django-connected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def response_change(self, request, obj):
        opts = self.model._meta
        preserved_filters = self.get_preserved_filters(request)
        msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(obj)}

        if '_reset_data' in request.POST:
            if obj.is_expired:
                obj.refresh_access_token()

            provider = obj.get_provider()
            profile_data = provider.get_profile_data(obj.raw_token)
            if profile_data is None:
                msg = _('Could not retrieve profile data for the %(name)s "%(obj)s" ') % msg_dict
                self.message_user(request, msg, messages.ERROR)
            else:
                obj.extra_data = provider.extract_extra_data(profile_data)
                obj.save()
                msg = _('The %(name)s "%(obj)s" was updated successfully.') % msg_dict
                self.message_user(request, msg, messages.SUCCESS)

            redirect_url = request.path
            redirect_url = add_preserved_filters(
                {'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
            return HttpResponseRedirect(redirect_url)

        return super(AccountAdmin, self).response_change(request, obj) 
Example #22
Source File: views.py    From Python-Programming-Blueprints with MIT License 5 votes vote down vote up
def my_orders(request):
    headers = {
        'Authorization': f'Token {settings.ORDER_SERVICE_AUTHTOKEN}',
        'Content-type': 'application/json'
    }

    get_order_endpoint = f'/api/customer/{request.user.id}/orders/get/'
    service_url = f'{settings.ORDER_SERVICE_BASEURL}{get_order_endpoint}'

    response = requests.get(
        service_url,
        headers=headers
    )

    if HTTPStatus(response.status_code) is HTTPStatus.OK:
        request_data = json.loads(response.text)
        context = {'orders': request_data}
    else:
        messages.add_message(
            request,
            messages.ERROR,
            ('Unfortunately, we could not retrieve your orders.'
             ' Try again later.'))
        context = {'orders': []}

    return render(request, 'main/my-orders.html', context) 
Example #23
Source File: views.py    From ideascube with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, *args, **kwargs):
        self.form = ExportEntryForm(self.request.GET)
        if self.form.is_valid():
            return super().get(*args, **kwargs)
        else:
            msg = _('Error while processing entries export')
            messages.add_message(self.request, messages.ERROR, msg)
            messages.add_message()
            return HttpResponseRedirect(reverse_lazy('monitoring:entry')) 
Example #24
Source File: views.py    From ideascube with GNU Affero General Public License v3.0 5 votes vote down vote up
def form_valid(self, form):
        count = 0
        module = form.cleaned_data['module']
        activity = form.cleaned_data['activity']
        partner = form.cleaned_data['partner']
        activity_select = form.cleaned_data.get('activity_list')
        if not activity and activity_select:
            activity = activity_select
        for serial in form.cleaned_data['serials']:
            try:
                user = user_model.objects.get(serial=serial)
            except user_model.DoesNotExist:
                msg = _('No user found with serial {serial}')
                msg = msg.format(serial=serial)
                messages.add_message(self.request, messages.ERROR, msg)
            else:
                Entry.objects.create(user=user, module=module,
                                     activity=activity, partner=partner)
                count += 1
        if count:
            msg = _('Created {count} entries')
            msg = msg.format(count=count)
            messages.add_message(self.request, messages.SUCCESS, msg)
        else:
            msg = _('No entry created.')
            messages.add_message(self.request, messages.WARNING, msg)
        return super().form_valid(form) 
Example #25
Source File: admin.py    From heltour with MIT License 5 votes vote down vote up
def approve(self, request, queryset):
        if not request.user.has_perm('tournament.invite_to_slack'):
            self.message_user(request, 'You don\'t have permissions to invite users to slack.',
                              messages.ERROR)
            return redirect('admin:tournament_registration_changelist')
        count = 0
        for reg in queryset:
            if reg.status == 'pending' and reg.validation_ok and not reg.validation_warning:
                workflow = ApproveRegistrationWorkflow(reg)

                send_confirm_email = workflow.default_send_confirm_email
                invite_to_slack = workflow.default_invite_to_slack
                default_section = workflow.default_section
                if workflow.is_late:
                    retroactive_byes = workflow.default_byes
                    late_join_points = workflow.default_ljp
                else:
                    retroactive_byes = None
                    late_join_points = None

                workflow.approve_reg(request, None, send_confirm_email, invite_to_slack,
                                     default_section, retroactive_byes, late_join_points)
                count += 1

        self.message_user(request, '%d approved.' % count, messages.INFO)
        return redirect('admin:tournament_registration_changelist') 
Example #26
Source File: admin.py    From heltour with MIT License 5 votes vote down vote up
def update_selected_player_ratings(self, request, queryset):
        #         try:
        usernames = [p.lichess_username for p in queryset.all()]
        for user_meta in lichessapi.enumerate_user_metas(usernames, priority=1):
            p = Player.objects.get(lichess_username__iexact=user_meta['id'])
            p.update_profile(user_meta)
        self.message_user(request, 'Rating(s) updated', messages.INFO)

    #         except:
    #             self.message_user(request, 'Error updating rating(s) from lichess API', messages.ERROR) 
Example #27
Source File: admin.py    From heltour with MIT License 5 votes vote down vote up
def move_to_next_round(self, request, queryset):
        if queryset.count() > 1:
            self.message_user(request, 'Late registrations can only be moved one at a time.',
                              messages.ERROR)
            return
        return redirect('admin:move_latereg', object_id=queryset[0].pk) 
Example #28
Source File: admin.py    From heltour with MIT License 5 votes vote down vote up
def simulate_results(self, request, queryset):
        if not settings.DEBUG and not settings.STAGING:
            self.message_user(request, 'Results can\'t be simulated in a live environment',
                              messages.ERROR)
            return
        if queryset.count() > 1:
            self.message_user(request, 'Results can only be simulated one round at a time',
                              messages.ERROR)
            return
        round_ = queryset[0]
        simulation.simulate_round(round_)
        self.message_user(request, 'Simulation complete.', messages.INFO)
        return redirect('admin:tournament_round_changelist') 
Example #29
Source File: admin.py    From heltour with MIT License 5 votes vote down vote up
def generate_pairings(self, request, queryset):
        if queryset.count() > 1:
            self.message_user(request, 'Pairings can only be generated one round at a time',
                              messages.ERROR)
            return
        return redirect('admin:generate_pairings', object_id=queryset[0].pk) 
Example #30
Source File: admin.py    From heltour with MIT License 5 votes vote down vote up
def force_alternate_board_update(self, request, queryset):
        try:
            for season in queryset.all():
                if not request.user.has_perm('tournament.manage_players', season.league):
                    raise PermissionDenied
                UpdateBoardOrderWorkflow(season).run(alternates_only=True)
            self.message_user(request, 'Alternate order updated.', messages.INFO)
        except IndexError:
            self.message_user(request, 'Error updating alternate order.', messages.ERROR)