Python django.contrib.messages.warning() Examples

The following are 30 code examples of django.contrib.messages.warning(). 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: views.py    From waliki with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def delete(request, slug):
    page = get_object_or_404(Page, slug=slug)
    data = request.POST if request.method == 'POST' else None
    form = DeleteForm(data)
    if form.is_valid():
        if form.cleaned_data['what'] == 'this':
            msg = _("The page %(slug)s was deleted") % {'slug': slug}
            page.delete()
        else:
            Page.objects.filter(slug__startswith=slug).delete()
            msg = _("The page %(slug)s and all its namespace was deleted") % {
                'slug': slug}

        messages.warning(request, msg)
        if request.is_ajax():
            return HttpResponse(json.dumps({'redirect': reverse('waliki_home')}), content_type="application/json")
        return redirect('waliki_home')

    if request.is_ajax():
        data = render_to_string('waliki/delete.html', {'page': page, 'form': form},
                                request=request)
        return HttpResponse(json.dumps({'data': data}), content_type="application/json")
    return render(request, 'waliki/delete.html', {'page': page, 'form': form}) 
Example #2
Source File: webdriver.py    From wagtail-tag-manager with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def scan(self):
        self.now = datetime.utcnow()

        try:
            self.init_browser()
            self.scan_webdriver()
        except Exception as e:
            self.scan_requests()
            messages.warning(
                self.request,
                _("WebDriver scan failed. Falling back to GET request method."),
            )
            messages.error(self.request, e)

        messages.success(
            self.request,
            _(
                "Created %d declaration(s) and updated %d declaration(s)."
                % (self.created, self.updated)
            ),
        ) 
Example #3
Source File: views.py    From pyt with GNU General Public License v2.0 6 votes vote down vote up
def project_details(request, project_id):
    proj = Project.objects.filter(
        users_assigned=request.user.id,
        pk=project_id)
    if not proj:
        messages.warning(
            request,
            'You are not authorized to view this project')
        return redirect('/taskManager/dashboard')
    else:
        proj = Project.objects.get(pk=project_id)
        user_can_edit = request.user.has_perm('project_edit')

        return render(request, 'taskManager/project_details.html',
                      {'proj': proj, 'user_can_edit': user_can_edit})

# A4: Insecure Direct Object Reference (IDOR) 
Example #4
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def post(self, request, pk=id):
        obj = get_object_or_404(Project, pk=pk, is_active=True)
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                sitefile = request.FILES['file']
                sites = sitefile.get_records()
                user = request.user
                task_obj = CeleryTaskProgress.objects.create(user=user, content_object = obj, task_type=0)
                if task_obj:
                    # import ipdb
                    # ipdb.set_trace()
                    task = bulkuploadsites.delay(task_obj.pk, user, sites, pk)
                    task_obj.task_id = task.id
                    task_obj.save()
                    messages.success(request, 'Sites are being uploaded. You will be notified in notifications list as well.')
                else:
                    messages.success(request, 'Sites cannot be updated a the moment.')
                return HttpResponseRedirect(reverse('fieldsight:proj-site-list', kwargs={'pk': pk}))
            except Exception as e:
                form.full_clean()
                form._errors[NON_FIELD_ERRORS] = form.error_class(['Sites Upload Failed, UnSupported Data', e])
                messages.warning(request, 'Site Upload Failed, UnSupported Data ')
        return render(request, 'fieldsight/upload_sites.html', {'obj': obj, 'form': form, 'project': pk}) 
Example #5
Source File: views.py    From pyt with GNU General Public License v2.0 6 votes vote down vote up
def change_password(request):

    if request.method == 'POST':
        user = request.user
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')

        if authenticate(username=user.username, password=old_password):
            if new_password == confirm_password:
                user.set_password(new_password)
                user.save()
                messages.success(request, 'Password Updated')
            else:
                messages.warning(request, 'Passwords do not match')
        else:
            messages.warning(request, 'Invalid Password')

    return render(request,
                  'taskManager/change_password.html',
                  {'user': request.user}) 
Example #6
Source File: admin.py    From cornerwise with MIT License 6 votes vote down vote up
def validate_importers(_, request, importers):
    when = datetime.now() - timedelta(days=30)
    for importer in importers:
        data = importer.updated_since(when)
        try:
            importer.validate(data)
        except jsonschema.exceptions.ValidationError as err:
            schema_path = "/".join(map(str, err.absolute_schema_path))
            messages.warning(
                request,
                f"Validation error for {importer} "
                f"at {schema_path}: {err.message}")
            messages.warning(
                request,
                str(reduce(lambda d, k: d[k], err.absolute_path, data)),
            )
        else:
            messages.info(request, f"{importer} successfully validated!") 
Example #7
Source File: views.py    From django-userlog with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def static(request):
    User = get_user_model()
    username_field = User.USERNAME_FIELD

    log = None

    username = request.GET.get('username')
    if username:
        try:
            User.objects.get(**{username_field: username})
        except User.DoesNotExist:
            messages.error(request, _("User {} not found.").format(username))
        else:
            log = get_log(username)
            if log:
                messages.info(request, _("Logs found for {}.").format(username))    # noqa
            else:
                messages.warning(request, _("No logs for {}.").format(username))    # noqa

    return render(request, 'userlog/static.html', {
        'title': _("Static log"),
        'log': log,
        'fieldname': User._meta.get_field(username_field).verbose_name,
    }) 
Example #8
Source File: views.py    From codesy with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_func(self):
        # settting the login_url determines redirect if test returns false
        if self.request.user.accepted_terms():
            self.login_url = self.reverse_lazy_with_param('identity')
        else:
            self.login_url = self.reverse_lazy_with_param('terms')
            return False

        user_account = self.request.user.account()
        try:
            identity_verified = user_account.identity_verified()
        except stripe.error.StripeError as e:
            if "that account does not exist" in e.message:
                messages.warning(self.request, 'stripe_account_error')
            return None
        return identity_verified 
Example #9
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 6 votes vote down vote up
def scan_scan_list(request: HttpRequest, scan_list_id: int) -> HttpResponse:
    """Schedule the scan of a scan list."""
    scan_list = get_object_or_404(
        ScanList.objects.prefetch_related(Prefetch(
            'sites',
            queryset=Site.objects.select_related('last_scan') \
                .annotate_most_recent_scan_start() \
                .annotate_most_recent_scan_end_or_null())
        ), pk=scan_list_id)
    was_any_site_scannable = scan_list.scan()
    if was_any_site_scannable:
        num_scanning_sites = Scan.objects.filter(end__isnull=True).count()
        messages.success(request,
            _("Scans for this list have been scheduled. "+ \
              "The total number of sites in the scanning queue "+ \
              "is %i (including yours)." % num_scanning_sites))
    else:
        messages.warning(request,
            _('All sites have been scanned recently. Please wait 30 minutes and try again.'))

    return redirect(reverse('frontend:view_scan_list', args=(scan_list_id,))) 
Example #10
Source File: views.py    From Collaboration-System with GNU General Public License v2.0 6 votes vote down vote up
def get(self, request, *args, **kwargs):
		if request.user.is_authenticated:
			self.object = self.get_object()
			if self.object.state.initial and self.object.created_by != request.user:
				return redirect('home')
			if self.object.state.final:
				messages.warning(request, 'Published content are not editable.')
				return redirect('article_view',pk=self.object.pk)
			community = self.get_community()
			if self.is_communitymember(request, community):
				role = self.get_communityrole(request, community)
				if canEditResourceCommunity(self.object.state.name, role.name, self.object, request):
					response=super(ArticleEditView, self).get(request, *args, **kwargs)
					if settings.REALTIME_EDITOR:
						sessionid = create_session_community(request, community.id)
						response.set_cookie('sessionID', sessionid)
					return response
				return redirect('article_view',pk=self.object.pk)
			return redirect('commnity_view',pk=community.pk)
		return redirect('login') 
Example #11
Source File: views.py    From Collaboration-System with GNU General Public License v2.0 6 votes vote down vote up
def get(self, request, *args, **kwargs):
		if request.user.is_authenticated:
			self.object = self.get_object()
			if self.object.state.initial and self.object.created_by != request.user:
				return redirect('home')
			if self.object.state.final:
				messages.warning(request, 'Published content are not editable.')
				return redirect('media_view',pk=self.object.pk)
			community = self.get_community()
			if self.is_communitymember(request, community):
				role = self.get_communityrole(request, community)
				if canEditResourceCommunity(self.object.state.name, role.name, self.object, request):
					response=super(MediaUpdateView, self).get(request, *args, **kwargs)
					return response
				return redirect('media_view',pk=self.object.pk)
			return redirect('community_view',pk=community.pk)
		return redirect('login') 
Example #12
Source File: views.py    From clist with Apache License 2.0 6 votes vote down vote up
def party_action(request, secret_key, action):
    party = get_object_or_404(Party.objects.for_user(request.user), secret_key=secret_key)
    coder = request.user.coder
    if coder.party_set.filter(pk=party.id).exists():
        if action == 'join':
            messages.warning(request, 'You are already in %s.' % party.name)
        elif action == 'leave':
            coder.party_set.remove(party)
            messages.success(request, 'You leave party %s.' % party.name)
    else:
        if action == 'join':
            party.coders.add(coder)
            messages.success(request, 'You join to %s.' % party.name)
        elif action == 'leave':
            messages.warning(request, 'You are not there in %s.' % party.name)
    return HttpResponseRedirect(reverse('coder:party', args=[party.slug])) 
Example #13
Source File: importexport.py    From weibo-analysis-system with MIT License 6 votes vote down vote up
def get_response(self, response, context, *args, **kwargs):
        has_view_perm = self.has_model_perm(self.model, 'view')
        if not has_view_perm:
            raise PermissionDenied

        export_format = self.request.GET.get('file_format')

        if not export_format:
            messages.warning(self.request, _('You must select an export format.'))
        else:
            formats = self.get_export_formats()
            file_format = formats[int(export_format)]()
            queryset = self.get_export_queryset(self.request, context)
            export_data = self.get_export_data(file_format, queryset, request=self.request)
            content_type = file_format.get_content_type()
            # Django 1.7 uses the content_type kwarg instead of mimetype
            try:
                response = HttpResponse(export_data, content_type=content_type)
            except TypeError:
                response = HttpResponse(export_data, mimetype=content_type)
            response['Content-Disposition'] = 'attachment; filename=%s' % (
                self.get_export_filename(file_format),
            )
            post_export.send(sender=None, model=self.model)
            return response 
Example #14
Source File: importexport.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def get_response(self, response, context, *args, **kwargs):
        has_view_perm = self.has_model_perm(self.model, 'view')
        if not has_view_perm:
            raise PermissionDenied

        export_format = self.request.GET.get('file_format')

        if not export_format:
            messages.warning(self.request, _('You must select an export format.'))
        else:
            formats = self.get_export_formats()
            file_format = formats[int(export_format)]()
            queryset = self.get_export_queryset(self.request, context)
            export_data = self.get_export_data(file_format, queryset, request=self.request)
            content_type = file_format.get_content_type()
            # Django 1.7 uses the content_type kwarg instead of mimetype
            try:
                response = HttpResponse(export_data, content_type=content_type)
            except TypeError:
                response = HttpResponse(export_data, mimetype=content_type)
            response['Content-Disposition'] = 'attachment; filename=%s' % (
                self.get_export_filename(file_format),
            )
            post_export.send(sender=None, model=self.model)
            return response 
Example #15
Source File: views.py    From django-blog-it with MIT License 6 votes vote down vote up
def user_status_update(request, pk):
    user = get_object_or_404(User, pk=pk)
    user_role = UserRole.objects.filter(user=request.user).last()
    if user_role:
        user_role = True if user_role.role == "Admin" else False
    else:
        user_role = False
    if request.user.is_superuser or user_role:
        if user.is_active:
            user.is_active = False
        else:
            user.is_active = True
        user.save()
    else:
        messages.warning(request, "You don't have permission")
    return HttpResponseRedirect(reverse_lazy("users")) 
Example #16
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def calculate_all_lettergrades(request, course_slug, activity_slug):
    course = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(CalLetterActivity, slug=activity_slug, offering=course, deleted=False)
    
    try:
        ignored = calculate_letter_grade(course,activity)
        if ignored==1:
            messages.warning(request, "Did not calculate letter grade for 1 manually-graded student.")
        elif ignored>1:
            messages.warning(request, "Did not calculate letter grade for %i manually-graded students." % (ignored))
    except ValidationError as e:
        messages.error(request, e.args[0])
    except NotImplementedError:
        return NotFoundResponse(request)

    return HttpResponseRedirect(activity.get_absolute_url()) 
Example #17
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def calculate_all(request, course_slug, activity_slug):
    course = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(CalNumericActivity, slug=activity_slug, offering=course, deleted=False)
    
    try:
        ignored, hiding_info = calculate_numeric_grade(course,activity)
        if hiding_info:
            messages.warning(request, "This activity is released to students, but the calculation uses unreleased grades. Calculations done with unreleased activities as zero to prevent leaking hidden info to students.")
        if ignored==1:
            messages.warning(request, "Did not calculate grade for 1 manually-graded student.")
        elif ignored>1:
            messages.warning(request, "Did not calculate grade for %i manually-graded students." % (ignored))
    except ValidationError as e:
        messages.error(request, e.args[0])
    except EvalException as e:
        messages.error(request, e.args[0])
    except NotImplementedError:
        return NotFoundResponse(request)

    return HttpResponseRedirect(activity.get_absolute_url()) 
Example #18
Source File: views.py    From tom_base with GNU General Public License v3.0 6 votes vote down vote up
def post(self, request):
        """
        Handles the POST requests to this view. Creates a StringIO object and passes it to ``import_targets``.

        :param request: the request object passed to this view
        :type request: HTTPRequest
        """
        csv_file = request.FILES['target_csv']
        csv_stream = StringIO(csv_file.read().decode('utf-8'), newline=None)
        result = import_targets(csv_stream)
        messages.success(
            request,
            'Targets created: {}'.format(len(result['targets']))
        )
        for error in result['errors']:
            messages.warning(request, error)
        return redirect(reverse('tom_targets:list')) 
Example #19
Source File: views.py    From django-blog-it with MIT License 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        if 'theme_ids[]' in request.GET:
            if request.GET.get('action') == 'False':
                Theme.objects.filter(id__in=request.GET.getlist('theme_ids[]')).update(enabled=False)
                messages.success(request, "Selected Theme's successfully updated as Disabled")
            elif request.GET.get('action') == 'Delete':
                Theme.objects.filter(id__in=request.GET.getlist('theme_ids[]')).delete()
                messages.success(request, "Selected Theme's successfully deleted!")
            return JsonResponse({'response': True})
        else:
            messages.warning(
                request, 'Please select at-least one record to perform this action')
            return JsonResponse({'response': False})


# social login 
Example #20
Source File: views.py    From pyt with GNU General Public License v2.0 5 votes vote down vote up
def reset_password(request):

    if request.method == 'POST':

        reset_token = request.POST.get('reset_token')

        try:
            userprofile = UserProfile.objects.get(reset_token = reset_token)
            if timezone.now() > userprofile.reset_token_expiration:
                # Reset the token and move on
                userprofile.reset_token_expiration = timezone.now()
                userprofile.reset_token = ''
                userprofile.save()
                return redirect('/taskManager/')

        except UserProfile.DoesNotExist:
            messages.warning(request, 'Invalid password reset token')
            return render(request, 'taskManager/reset_password.html')

        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')
        if new_password != confirm_password:
            messages.warning(request, 'Passwords do not match')
            return render(request, 'taskManager/reset_password.html')

        # Reset the user's password + remove the tokens
        userprofile.user.set_password(new_password)
        userprofile.reset_token = ''
        userprofile.reset_token_expiration = timezone.now()
        userprofile.user.save()
        userprofile.save()

        messages.success(request, 'Password has been successfully reset')
        return redirect('/taskManager/login')

    return render(request, 'taskManager/reset_password.html')

# Vuln: Username Enumeration 
Example #21
Source File: students.py    From django-multiple-user-types-example with MIT License 5 votes vote down vote up
def take_quiz(request, pk):
    quiz = get_object_or_404(Quiz, pk=pk)
    student = request.user.student

    if student.quizzes.filter(pk=pk).exists():
        return render(request, 'students/taken_quiz.html')

    total_questions = quiz.questions.count()
    unanswered_questions = student.get_unanswered_questions(quiz)
    total_unanswered_questions = unanswered_questions.count()
    progress = 100 - round(((total_unanswered_questions - 1) / total_questions) * 100)
    question = unanswered_questions.first()

    if request.method == 'POST':
        form = TakeQuizForm(question=question, data=request.POST)
        if form.is_valid():
            with transaction.atomic():
                student_answer = form.save(commit=False)
                student_answer.student = student
                student_answer.save()
                if student.get_unanswered_questions(quiz).exists():
                    return redirect('students:take_quiz', pk)
                else:
                    correct_answers = student.quiz_answers.filter(answer__question__quiz=quiz, answer__is_correct=True).count()
                    score = round((correct_answers / total_questions) * 100.0, 2)
                    TakenQuiz.objects.create(student=student, quiz=quiz, score=score)
                    if score < 50.0:
                        messages.warning(request, 'Better luck next time! Your score for the quiz %s was %s.' % (quiz.name, score))
                    else:
                        messages.success(request, 'Congratulations! You completed the quiz %s with success! You scored %s points.' % (quiz.name, score))
                    return redirect('students:quiz_list')
    else:
        form = TakeQuizForm(question=question)

    return render(request, 'classroom/students/take_quiz_form.html', {
        'quiz': quiz,
        'question': question,
        'form': form,
        'progress': progress
    }) 
Example #22
Source File: views.py    From cornerwise with MIT License 5 votes vote down vote up
def activate_subscription(request, user, sub):
    sub.activate()
    sub.save()
    messages.success(request, "Subscription activated.")

    if not user.email:
        messages.warning(request, "There is no email address associated with this account")

    return redirect(reverse(manage)) 
Example #23
Source File: views.py    From pasportaservo with GNU Affero General Public License v3.0 5 votes vote down vote up
def form_valid(self, form):
        response = super().form_valid(form)
        if form.previous_email != form.instance.email:
            messages.warning(self.request, extra_tags='eminent',
                             message=_("A confirmation email has been sent. "
                                       "Please check your mailbox to complete the process."))
        return response 
Example #24
Source File: views.py    From tom_base with GNU General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        """
        Method that handles POST requests for the ``DataProductSaveView``. Gets the observation facility that created
        the data and saves the selected data products as ``DataProduct`` objects. Redirects to the
        ``ObservationDetailView`` for the specific ``ObservationRecord``.

        :param request: Django POST request object
        :type request: HttpRequest
        """
        service_class = get_service_class(request.POST['facility'])
        observation_record = ObservationRecord.objects.get(pk=kwargs['pk'])
        products = request.POST.getlist('products')
        if not products:
            messages.warning(request, 'No products were saved, please select at least one dataproduct')
        elif products[0] == 'ALL':
            products = service_class().save_data_products(observation_record)
            messages.success(request, 'Saved all available data products')
        else:
            for product in products:
                products = service_class().save_data_products(
                    observation_record,
                    product
                )
                messages.success(
                    request,
                    'Successfully saved: {0}'.format('\n'.join(
                        [str(p) for p in products]
                    ))
                )
        return redirect(reverse(
            'tom_observations:detail',
            kwargs={'pk': observation_record.id})
        ) 
Example #25
Source File: groups.py    From tom_base with GNU General Public License v3.0 5 votes vote down vote up
def add_selected_to_grouping(targets_ids, grouping_object, request):
    """
    Adds all selected targets to a ``TargetList``. Successes, warnings, and errors result in messages being added to the
    request with the appropriate message level.

    :param targets_ids: list of selected targets
    :type targets_ids: list

    :param grouping_object: ``TargetList`` to add targets to
    :type grouping_object: TargetList

    :param request: request object passed to the calling view
    :type request: HTTPRequest
    """
    success_targets = []
    warning_targets = []
    failure_targets = []
    for target_id in targets_ids:
        try:
            target_object = Target.objects.get(pk=target_id)
            if not request.user.has_perm('tom_targets.view_target', target_object):
                failure_targets.append((target_object.name, 'Permission denied.',))
            elif target_object in grouping_object.targets.all():
                warning_targets.append(target_object.name)
            else:
                grouping_object.targets.add(target_object)
                success_targets.append(target_object.name)
        except Exception as e:
            failure_targets.append((target_object.pk, e,))
    messages.success(request, "{} target(s) successfully added to group '{}'."
                              .format(len(success_targets), grouping_object.name))
    if warning_targets:
        messages.warning(request, "{} target(s) already in group '{}': {}"
                                  .format(len(warning_targets), grouping_object.name, ', '.join(warning_targets)))
    for failure_target in failure_targets:
        messages.error(request, "Failed to add target with id={} to group '{}'; {}"
                                .format(failure_target[0], grouping_object.name, failure_target[1])) 
Example #26
Source File: views.py    From tom_base with GNU General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        """
        Handles the POST requests to this view. Creates a ``Target`` for each alert sent in the POST. Redirects to the
        ``TargetListView`` if multiple targets were created, and the ``TargetUpdateView`` if only one was created.
        Redirects to the ``RunQueryView`` if no ``Target`` objects. were successfully created.
        """
        query_id = self.request.POST['query_id']
        broker_name = self.request.POST['broker']
        broker_class = get_service_class(broker_name)
        alerts = self.request.POST.getlist('alerts')
        errors = []
        if not alerts:
            messages.warning(request, 'Please select at least one alert from which to create a target.')
            return redirect(reverse('tom_alerts:run', kwargs={'pk': query_id}))
        for alert_id in alerts:
            cached_alert = cache.get('alert_{}'.format(alert_id))
            if not cached_alert:
                messages.error(request, 'Could not create targets. Try re running the query again.')
                return redirect(reverse('tom_alerts:run', kwargs={'pk': query_id}))
            generic_alert = broker_class().to_generic_alert(json.loads(cached_alert))
            target = generic_alert.to_target()
            try:
                target.save()
                broker_class().process_reduced_data(target, json.loads(cached_alert))
                for group in request.user.groups.all().exclude(name='Public'):
                    assign_perm('tom_targets.view_target', group, target)
                    assign_perm('tom_targets.change_target', group, target)
                    assign_perm('tom_targets.delete_target', group, target)
            except IntegrityError:
                messages.warning(request, f'Unable to save {target.name}, target with that name already exists.')
                errors.append(target.name)
        if (len(alerts) == len(errors)):
            return redirect(reverse('tom_alerts:run', kwargs={'pk': query_id}))
        elif (len(alerts) == 1):
            return redirect(reverse(
                'tom_targets:update', kwargs={'pk': target.id})
            )
        else:
            return redirect(reverse(
                'tom_targets:list')
            ) 
Example #27
Source File: views.py    From pasportaservo with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            # Only anonymous (non-authenticated) users are expected to access this page.
            return HttpResponseRedirect(self.get_authenticated_redirect_url())
        request_id = request.session.pop('restore_request_id', None)
        if request_id is None or not isinstance(request_id[1], float):
            # When the restore request ID is missing or invalid, just show the login page.
            return HttpResponseRedirect(reverse_lazy('login'))
        if datetime.now() - datetime.fromtimestamp(request_id[1]) > timedelta(hours=1):
            # When the restore request ID is expired (older than 1 hour), redirect to the login page.
            # This is to prevent abuse, when the user leaves their browser or device open and
            # a different person attempts to (mis)use the restoration request functionality...
            messages.warning(self.request, _("Something misfunctioned. Please log in again and retry."))
            return HttpResponseRedirect(reverse_lazy('login'))
        # Otherwise, send mail to admins.
        send_mail(
            '{prefix}{subject}'.format(
                prefix=settings.EMAIL_SUBJECT_PREFIX,
                subject=gettext(
                    # xgettext:python-brace-format
                    "Note to admin: User requests to reactivate their account; ref: {}."
                ).format(request_id[0])),
            "--",
            None,
            ['{} <{}>'.format(nick, addr) for nick, addr in settings.ADMINS],
            fail_silently=False)
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context) 
Example #28
Source File: views.py    From pasportaservo with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        """
        Show the warning about consequences of not accepting the agreement.
        """
        agreement = request.session.pop('agreement_rejected', None)
        if not agreement:
            return HttpResponse()
        request.session['agreement_rejected_final'] = agreement
        return super().get(request, *args, **kwargs) 
Example #29
Source File: forms.py    From palanaeum with GNU Affero General Public License v3.0 5 votes vote down vote up
def save(self, commit=True):
        if self.cleaned_data['update_entry_dates']:
            messages.warning(get_request(), _("Sorry, we can't update entry dates right now :("))
            # FIXME: This doesn't work any more, as entry dates are stored in EntryVersion objects now.
            # Entry.objects.filter(event=self.instance, date=self.original_date).update(date=self.cleaned_data['date'])
        super(EventForm, self).save()
        tags = self.cleaned_data['tags'][1:-1]  # No [] at ends
        tags = tags.split(',')  # Separate tags
        tags = [str(tag).strip("'\"") for tag in tags]
        self.instance.update_tags(", ".join(tags))
        return self.instance 
Example #30
Source File: staff_views.py    From palanaeum with GNU Affero General Public License v3.0 5 votes vote down vote up
def edit_entry(request, entry_id=None, event_id=None):
    """
    Display an edit page for Entry object.
    """
    if not is_contributor(request):
        messages.warning(request, _('This page is for contributors only.'))
        return redirect('index')

    if entry_id is None:
        entry = Entry()
        entry.event = get_object_or_404(Event, pk=event_id)
        version = EntryVersion(entry=entry)
        version.entry_date = entry.event.date
        entry.created_by = request.user
        entry.set_order_last()
    else:
        entry = get_object_or_404(Entry, pk=entry_id)

    if entry_id is not None:
        snippets = list(Snippet.all_visible.filter(entry=entry))
        images = list(ImageSource.all_visible.filter(entry=entry))
    else:
        snippets = []
        images = []

    return render(request, 'palanaeum/staff/entry_edit_form.html', {'entry': entry, 'event': entry.event,
                                                                    'snippets': snippets,
                                                                    'images': images})