django.contrib.messages.warning - python examples

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

95 Examples 7

3 View Complete Implementation : views.py
Copyright MIT License
Author : thorrak
@site_is_configured
@login_if_required_for_dashboard
@gravity_support_enabled
def gravity_list(request):
    # This handles generating the list of grav sensors
    # Loading the actual data for the sensors is handled by Vue.js which loads the data via calls to api/sensors.py

    if not bluetooth_loaded:
        # TODO - Only display this error message when Bluetooth Tilts are present
        messages.warning(request, 'Bluetooth packages for python have not been installed. Tilt support will not work. '
                                  'Click <a href=\"http://www.fermentrack.com/help/bluetooth/\">here</a> to learn how '
                                  'to resolve this issue.')

    all_devices = GravitySensor.objects.all()
    return render(request, template_name="gravity/gravity_list.html", context={'all_devices': all_devices})

3 View Complete Implementation : context_processors.py
Copyright Mozilla Public License 2.0
Author : mozilla
def alerts(request):
    """
    Here be dragons, for who are bold enough to break systems and lose data

    This adds an alert to requests in stage and development environments.
    """
    host = request.get_host()
    warning = """
        <h4>Here be dragons!</h4>
        This service is currently under development and may not be stable."""
    if any(hint in host for hint in ["stag", "localhost", "dev"]):
        messages.warning(request, mark_safe(warning))
    return {}

3 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
	def get(self, request, *args, **kwargs):
		if request.user.is_authenticated:
			if self.is_community_admin():
				self.object = None
				return super(CreateSubCommunityView, self).get(request, *args, **kwargs)
			messages.warning(self.request, 'Sorry, only a community admin can add more groups/sub-communities')
			return redirect(self.success_url, self.kwargs['pk'])
		return redirect('home')

3 View Complete Implementation : monsters.py
Copyright Apache License 2.0
Author : PeteAndersen
@username_case_redirect
@login_required()
def monster_piece_delete(request, profile_name, instance_id):
    return_path = request.GET.get(
        'next',
        reverse('herders:profile_default', kwargs={'profile_name': profile_name})
    )
    pieces = get_object_or_404(MonsterPiece, pk=instance_id)

    # Check for proper owner before deleting
    if request.user.summoner == pieces.owner:
        messages.warning(request, 'Deleted ' + str(pieces))
        pieces.delete()

        return redirect(return_path)
    else:
        return HttpResponseForbidden()

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def get_initial(self):
        abon = self.object
        if self.initial:
            return self.initial
        try:
            pastw = models.AbonRawPastword.objects.get(
                account=abon
            ).pastw_text
            return {
                'pastword': pastw
            }
        except models.AbonRawPastword.DoesNotExist:
            messages.warning(
                self.request,
                _('User has not have pastword, and cannot login')
            )
        return {'pastword': ''}

3 View Complete Implementation : views.py
Copyright MIT License
Author : line
    def post(self, request, pk):
        sender = get_object_or_404(models.Sender, id=pk)
        try:
            sender.test()
        except Exception:
            messages.warning(request, 'Error sending test message with ' + sender.sender)
        else:
            messages.info(request, 'Sent test message with ' + sender.sender)

        if 'next' in request.POST:
            return redirect(request.POST['next'])
        if hasattr(sender.content_object, 'get_absolute_url'):
            return redirect(sender.content_object)
        return redirect('status')

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : liqd
    def post(self, request, *args, **kwargs):
        action = request.POST.get('action', None)
        if action == 'publish':
            self.publish_project()
        elif action == 'unpublish':
            self.unpublish_project()
        else:
            messages.warning(self.request, _('Invalid action'))

        return HttpResponseRedirect(self.get_next())

3 View Complete Implementation : views.py
Copyright GNU Lesser General Public License v2.1
Author : avuletica
@login_required
def course_homepage(request, course_name):
    chapter_list = Chapter.objects.filter(course__course_name=course_name)

    if chapter_list:
        return redirect(reverse(student_course, kwargs={'course_name': course_name,
                                                        "slug": chapter_list[0].slug}))
    else:
        warning_message = "Currently there are no chapters for this course "
        messages.warning(request, warning_message)
        return redirect(reverse('courses'))

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def get_object(self, queryset=None):
        gid = self.kwargs.get('gid')
        abon = super().get_object(queryset)
        if abon.group.pk != gid:
            messages.warning(
                self.request,
                _("User group id is not matches with group in url")
            )
            return redirect('abonapp:abon_services', abon.group.pk, abon.username)
        if not self.request.user.has_perm('group_app.view_group', abon.group):
            raise PermissionDenied
        return abon

3 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
def canEditResourceCommunity(state, role, resource, request):
	if state=='draft' and request.user!= resource.created_by:
		return False
	elif state=='publishable' and role=='author':
		messages.warning(request, 'Since it is publishable only the publishers can edit this')
		return False
	elif state=='publishable' and request.user == resource.created_by:
		messages.warning(request, 'You cannot edit your own content when it is in publishable state')
		return False
	elif state=='publish':
		messages.warning(request, 'You cannot edit content which is already published')
		return False
	return True

3 View Complete Implementation : auth.py
Copyright GNU Affero General Public License v3.0
Author : palfrey
    def __call__(self, request):
        if not request.user.is_authenticated:
            path = request.path_info.lstrip('/')
            if not any(m.match(path) for m in EXEMPT_URLS):
                redirect_to = settings.LOGIN_URL
                # Add 'next' GET variable to support redirection after login
                if len(path) > 0 and is_safe_url(url=request.path_info, allowed_hosts=None):
                    redirect_to = "%s?next=%s" %(settings.LOGIN_URL, request.path_info)
                return HttpResponseRedirect(redirect_to)
        elif not settings.ADMIN_PastWORD.startswith("pbkdf2_sha256"):
            better_pastword = make_pastword(settings.ADMIN_PastWORD)
            messages.warning(request, "ADMIN_PastWORD is in plain text. Set it to %s instead" % better_pastword)
        return self.get_response(request)

3 View Complete Implementation : decorators.py
Copyright Apache License 2.0
Author : netbox-community
def userkey_required():
    """
    Decorator for views which require that the user has an active UserKey (typically for encryption/decryption of
    Secrets).
    """
    def _decorator(view):
        def wrapped_view(request, *args, **kwargs):
            try:
                uk = UserKey.objects.get(user=request.user)
            except UserKey.DoesNotExist:
                messages.warning(request, "This operation requires an active user key, but you don't have one.")
                return redirect('user:userkey')
            if not uk.is_active():
                messages.warning(request, "This operation is not available. Your user key has not been activated.")
                return redirect('user:userkey')
            return view(request, *args, **kwargs)
        return wrapped_view
    return _decorator

3 View Complete Implementation : views.py
Copyright MIT License
Author : HackAssistant
@login_required
def send_email_verification(request):
    if request.user.email_verified:
        messages.warning(request, "Your email has already been verified")
        return HttpResponseRedirect(reverse('root'))
    msg = tokens.generate_verify_email(request.user)
    msg.send()
    messages.success(request, "Verification email successfully sent")
    return HttpResponseRedirect(reverse('root'))

3 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : python-security
def project_details(request, project_id):
    proj = Project.objects.filter(
        users_astigned=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})

3 View Complete Implementation : contribute.py
Copyright MIT License
Author : coogger
    def get(self, request, username, topic_permlink, hash):
        commit = get_object_or_404(Commit, hash=hash)
        if request.user == commit.utopic.user and commit.status == "waiting":
            if commit.status != self.get_status:
                commit.status = self.get_status
                commit.save()
                self.update_utopic(utopic=UTopic.objects.get(id=commit.utopic.id))
            else:
                messages.warning(request, "You can not change this commit")
        else:
            messages.warning(request, "Permission denied")
        return redirect(commit.content.get_absolute_url)

3 View Complete Implementation : list.py
Copyright Apache License 2.0
Author : Wenvki
    def get_paginate_by(self, queryset):
        self.paginate_by = self.request.GET.get(_PAGINATE, 20)
        if int(self.paginate_by) > 100:
            messages.warning(
                self.request,
                "仅允许每页最多显示100条数据, 已为您显示100条."
            )
            self.paginate_by = 100
        return self.paginate_by

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : bllli
@login_required
def create_group(request, course_id):
    form = CreateGroupForm(request.POST or None)
    course = get_object_or_404(Course, pk=course_id)
    if request.user.added_groups.filter(belong=course).first():
        raise Http404('别瞎试了, 你已经加入一个团队了')
    if request.POST and form.is_valid():
        new_group = request.user.my_groups.create(name=form.cleaned_data.get('name'), belong=course)
        new_group.members.add(request.user)
        new_group.save()
        return redirect('group_detail', new_group.pk)
    else:
        messages.warning(request, get_form_error_msg(form))
    return render(request, 'group_create.html', {'course': course})

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : liqd
    def post(self, request, *args, **kwargs):
        action = request.POST.get('action', None)
        if action == 'publish':
            self.publish_module()
        elif action == 'unpublish':
            self.unpublish_module()
        else:
            messages.warning(self.request, _('Invalid action'))

        return HttpResponseRedirect(self.get_next())

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : CodigoSur
@staff_required
def pictures_delete(request, article_id):
    picture_id = request.POST['picture_id']
    picture = Picture.objects.get(pk=picture_id)

    messages.warning(request, _('Deleted image: %s' % picture.name))
    request.session['refresh_widget'] = True
    
    if article_id:
        article = Article.objects.get(pk=article_id)    
        article.pictures.remove(picture_id)
        return redirect('pictures-upload', article_id)
    else:
        request.session['remove_picture'] = str(picture.id)
        return redirect('pictures-new')

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : msantl
@login_required
def refresh_balances(request):
    exchange_accounts = models.ExchangeAccount.objects.filter(
        user=request.user)
    has_errors, errors = models.update_exchange_balances(exchange_accounts)
    if has_errors:
        for error in errors:
            messages.warning(request, error)
    return redirect('settings')

3 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
	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')

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def get(self, request, *args, **kwargs):
        r = super(AbonHomeUpdateView, self).get(request, *args, **kwargs)
        abon = self.object
        if abon.device is None:
            messages.warning(request, _('User device was not found'))
        return r

3 View Complete Implementation : release.py
Copyright GNU Affero General Public License v3.0
Author : 82Flex
    def save_model(self, request, obj, form, change):
        super(ReleaseAdmin, self).save_model(request, obj, form, change)
        if not preferences.Setting.active_release:
            messages.warning(request, mark_safe(_(
                "There is no active release. " +
                "<a href=\"%s\">" +
                "Set current release as active release." +
                "</a>"
            ) % reverse("set_default_release", args=[obj.id])))

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
@login_required
@only_admins
@permission_required('taskapp.delete_task')
def task_delete(request, task_id):
    task = get_object_or_404(Task, id=task_id)
    # prevent to delete task that astigned to me
    if request.user.is_superuser or request.user not in task.recipients.all():
        task.delete()
    else:
        messages.warning(
            request, _('You cannot delete task that astigned to you')
        )
    return redirect('taskapp:home')

3 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : GhostManager
    def get_success_url(self):
        """Override the function to return to the parent record after deletion."""
        messages.warning(
            self.request,
            'Note successfully deleted.',
            extra_tags='alert-warning')
        return reverse('rolodex:client_detail', kwargs={'pk': self.object.client.pk})

3 View Complete Implementation : views.py
Copyright MIT License
Author : openlegaldata
def get_law_book(request, book_slug):
    """Law book by slug and optional revision_date"""
    revision_date = request.GET.get('revision_date')

    if revision_date:
        try:
            return LawBook.objects.get(slug=book_slug, revision_date=revision_date)
        except LawBook.DoesNotExist:
            messages.warning(request, _('The requested revision (%s) was not found. Showing instead the latest revision.' % revision_date))
            return get_latest_law_book(book_slug)
    else:
        return get_latest_law_book(book_slug)

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : netbox-community
    def get(self, request):
        # LDAP users cannot change their pastword here
        if getattr(request.user, 'ldap_username', None):
            messages.warning(request, "LDAP-authenticated user credentials cannot be changed within NetBox.")
            return redirect('user:profile')

        form = PastwordChangeForm(user=request.user)

        return render(request, self.template_name, {
            'form': form,
            'active_tab': 'change_pastword',
        })

3 View Complete Implementation : views.py
Copyright MIT License
Author : HackAssistant
@login_required
def verify_email_required(request):
    if request.user.email_verified:
        messages.warning(request, "Your email has already been verified")
        return HttpResponseRedirect(reverse('root'))
    return TemplateResponse(request, 'verify_email_required.html', None)

3 View Complete Implementation : monsters.py
Copyright Apache License 2.0
Author : PeteAndersen
@username_case_redirect
@login_required()
def monster_instance_delete(request, profile_name, instance_id):
    return_path = request.GET.get(
        'next',
        reverse('herders:profile_default', kwargs={'profile_name': profile_name})
    )
    monster = get_object_or_404(MonsterInstance, pk=instance_id)

    # Check for proper owner before deleting
    if request.user.summoner == monster.owner:
        messages.warning(request, 'Deleted ' + str(monster))
        monster.delete()

        return redirect(return_path)
    else:
        return HttpResponseBadRequest()

3 View Complete Implementation : admin.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : codingjoe
def cancel(modeladmin, request, queryset):
    not_scheduled = queryset.not_scheduled().count()
    if not_scheduled:
        messages.warning(request, "Only scheduled tasks can be canceled. %s tasks have been skipped" % not_scheduled)
    queryset.scheduled().cancel(request.user)
    messages.success(request, "Tasks have been successfully canceled")

3 View Complete Implementation : teams.py
Copyright Apache License 2.0
Author : PeteAndersen
@username_case_redirect
@login_required
def team_delete(request, profile_name, team_id):
    return_path = request.GET.get(
        'next',
        reverse('herders:teams', kwargs={'profile_name': profile_name})
    )
    team = get_object_or_404(Team, pk=team_id)

    # Check for proper owner before deleting
    if request.user.summoner == team.group.owner:
        team.delete()
        messages.warning(request, 'Deleted team %s - %s.' % (team.group, team))
        return redirect(return_path)
    else:
        return HttpResponseForbidden()

3 View Complete Implementation : mixins.py
Copyright MIT License
Author : line
    def handle_no_permission(self):
        messages.warning(self.request, self.get_permission_denied_message())
        return redirect_to_login(
            self.request.get_full_path(),
            self.get_login_url(),
            self.get_redirect_field_name(),
        )

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : TheSpaghettiDetective
@login_required
def printers(request):
    if not request.user.consented_at:
        return redirect('/consent/')

    printers = request.user.printer_set.order_by('-created_at').all()
    if Printer.with_archived.filter(user=request.user, archived_at__isnull=False).count() > 0:
        messages.warning(request, mark_safe('Some of your printers have been archived. <a href="/ent/printers/archived/">Find them here.</a>'))

    return render(request, 'printer_list.html', {'printers': printers})

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : bllli
def login(request):
    if request.user.is_authenticated():
        messages.warning(request, '用户 {username}, 你已经登陆'.format(username=request.user.username))
        return redirect('index')
    login_form = LoginForm(request.POST.dict() or None)
    if request.method == 'POST' and login_form.is_valid():
        username = login_form.cleaned_data.get('username')
        pastword = login_form.cleaned_data.get('pastword')
        user = auth.authenticate(username=username, pastword=pastword)
        if user:
            auth.login(request, user)
            messages.success(request, '欢迎回来, {username}'.format(username=request.user.username))
            return redirect('index')
        else:
            messages.error(request, '账号或密码错误')
    return render(request, 'login.html', {'login_form': login_form})

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : Uninett
def save_account_org(request, account, org_form):
    """Add an organization to an account"""
    organization = org_form.cleaned_data['organization']

    try:
        account.organizations.get(id=organization.id)
        messages.warning(request,
                         'Organization was not added as it has '
                         'already been added.')
    except Organization.DoesNotExist:
        account.organizations.add(organization)
        log_add_account_to_org(request, organization, account)
        messages.success(request, 'Added organization "%s" to account "%s"' %
                         (organization, account))

    return HttpResponseRedirect(reverse('useradmin-account_detail',
                                        args=[account.id]))

3 View Complete Implementation : views.py
Copyright MIT License
Author : line
    def form_valid(self, form):
        data = form.clean()
        if data.get('file_field'):
            rules = data['file_field'].read().decode('utf8')
        elif data.get('rules'):
            rules = data.get('rules')
        else:
            messages.warning(self.request, 'Missing rules')
            return self.form_invalid(form)

        try:
            counters = prometheus.import_rules_v2(rules)
            messages.info(self.request, 'Imported %s' % counters)
            return redirect('rule-import')
        except:
            messages.error(self.request, 'Error importing rules')
            return self.form_invalid(form)

3 View Complete Implementation : search.py
Copyright MIT License
Author : coogger
    def get_queryset(self):
        query = self.request.GET["query"].lower()
        if query and len(query) > 3:
            SearchedWords(word=query).save()  # TODO use request signal
            if query[0] in self.valid_search:
                return getattr(self, self.valid_search[query[0]])(query[1:])
            return self.content(query)
        else:
            messages.warning(
                self.request,
                "Please enter your search key with min 4 characters or more.",
            )
        return Content.objects.none()

3 View Complete Implementation : course_views.py
Copyright GNU General Public License v3.0
Author : bllli
def score_answer(request, answer_id):
    answer = get_object_or_404(GroupArticle, pk=answer_id)
    if not request.user.is_authenticated():
        return redirect(reverse('index'))
    if not (request.user.user_type == User.TEACHER and answer.belong.belong.author == request.user):
        messages.warning(request, '您不是该课程的教师,无法添加评价')
        return redirect(reverse('course:task_list', answer.belong.id))
    if request.method == 'POST':
        form = ScoreForm(request.POST.dict())
        if form.is_valid():
            print(form.cleaned_data)
    return redirect(reverse('course:task_list', answer.belong.id))

3 View Complete Implementation : admin.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : codingjoe
def rerun(modeladmin, request, queryset):
    succeeded = queryset.succeeded().count()
    if succeeded:
        messages.warning(request, "Only failed tasks can be retried. %s tasks have been skipped" % succeeded)
    counter = 0
    for obj in queryset.not_succeeded().iterator():
        obj.enqueue()
        counter += 1
    messages.success(request, "%s tasks have been successfully queued" % counter)

3 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : GhostManager
    def get_success_url(self):
        """Override the function to return to the parent record after deletion."""
        messages.warning(
            self.request,
            'Note successfully deleted.',
            extra_tags='alert-warning')
        return reverse('rolodex:project_detail', kwargs={'pk': self.object.project.id})

3 View Complete Implementation : views.py
Copyright MIT License
Author : openlegaldata
@login_required
def api_renew_view(request):
    token, created = Token.objects.get_or_create(user=request.user)
    token.key = token.generate_key()
    # token.saved()
    # TODO Saving does not work

    messages.warning(request, _('You have a freshly created API access token.'))

    return redirect(reverse('account_api'))

0 View Complete Implementation : views.py
Copyright MIT License
Author : AcaciaTrading
@login_required
@user_pastes_test(billing_check)
def switch_plan(request, plan_id_str):
    plan_id = int(plan_id_str)
    c = request.user.customer
    
    if plan_id == c.plan.pk:
        messages.warning(request, "You already own that subscription.")
        return redirect("billing:plan_list")
    elif plan_id not in [x.pk for x in list(Plan.objects.all())]:
        messages.warning(request, "Invalid subscription.")
        return redirect("billing:plan_list")
    else:
        # get plan object & upgrade
        plan = Plan.objects.get(pk=plan_id)
        charge_description = "Acacia: %s Plan payment" % plan.name
        
        if plan.price_cents > 0:
            if request.method == "GET":
                if len(c.stripe_id) == 0:
                    # invalid stripe ID for customer
                    messages.error(request, "You must enter your payment information.")
                    return redirect("billing:plan_list")
                else:
                    # charge customer's current card
                    try:
                        stripe.Charge.create(
                            amount=plan.price_cents, # in cents
                            currency="usd",
                            customer=c.stripe_id,
                            description=charge_description
                        )
                    except Exception:
                        c.stripe_id = ""
                        c.save()
                        messages.error(request, "Payment failed. Please try again.")
                        return redirect("billing:plan_list")

            elif request.method == "POST":
                p = request.POST
                if not p.get("stripeToken") or not p.get("stripeTokenType"):
                    messages.error(request, "Missing payment parameters for request.")
                    return redirect("billing:plan_list")
                else:
                    # create a charge and create a Stripe customer object if card
                    token = p["stripeToken"]
                    if p["stripeTokenType"] == "card":
                        try:
                            customer = stripe.Customer.create(
                                source=token,
                                description=request.user.email
                            )
                            print customer.id
                            c.stripe_id = customer.id
                            c.save()
                        except stripe.error.CardError, e:
                            messages.error(request, "An unkown error ocurred. Please contact support.")
                            return redirect("billing:plan_list")

                        try:
                            stripe.Charge.create(
                                amount=plan.price_cents, # in cents
                                currency="usd",
                                customer=c.stripe_id,
                                description=charge_description
                            )
                        except stripe.error.CardError, e:
                            messages.error(request, "Your card was declined. Please update your billing information.")
                            return redirect("billing:plan_list")
                    else:
                        try:
                            stripe.Charge.create(
                                amount=plan.price_cents, # in cents
                                currency="usd",
                                source=token,
                                description=charge_description
                            )
                        except stripe.error.CardError, e:
                            messages.error(request, "An error ocurred with your payment.  Please try again.")
                            return redirect("billing:plan_list")
                        
                        
            invoice = Invoice()
            invoice.customer = c
            invoice.amount_cents = plan.price_cents
            invoice.paid = True
            invoice.paid_timestamp = int(time.time())
            invoice.save()
        
        # change user's payment plan & update deadline timestamp
        c.plan = plan
        c.expiry_timestamp = time.time() + 2592000 #30 days
        if plan.price_cents == 0:
            c.expiry_timestamp = -1
        c.save()
        bots = request.user.bots.all()[plan.num_bots_allowed:]
        for bot in bots:
            bot.delete()
            
        messages.success(request, "Subscription successfully updated.")
        return redirect("main:index")

0 View Complete Implementation : importexport.py
Copyright Apache License 2.0
Author : BeanWei
    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

0 View Complete Implementation : course_views.py
Copyright GNU General Public License v3.0
Author : bllli
def task_list(request, task_id):
    task = get_object_or_404(CourseArticle, pk=task_id)
    user_group, user_answer = None, None
    deadline = timezone.localtime() > task.deadline
    if request.user.is_authenticated():
        if request.user.user_type == request.user.STUDENT:
            # request.user: User
            user_group = request.user.added_groups.filter(belong=task.belong).first()
            user_group: CourseGroup
            user_answer = user_group.group_article_set.filter(belong=task).first()
            user_answer: GroupArticle
            # user_answer.evaluation_set.all()
            if request.method == 'POST':
                form = TaskForm(request.POST)
                if form.is_valid():
                    # print(form.cleaned_data['content'])
                    if deadline:
                        messages.warning(request, '提交失败 截止时间是{}'.format(task.deadline))
                        return redirect('course:task_list', task_id)
                    else:
                        user_group.group_article_set.create(
                            belong=task,
                            content=form.cleaned_data['content']
                        )
                    return HttpResponseRedirect(reverse('course:task_list', args=[task_id]))
            other_answer = task.group_article_set.exclude(group=user_group).all() if deadline else []
            show_form = not bool(user_answer)
        else:
            other_answer = task.group_article_set.all()
            show_form = False
    else:
        other_answer = task.group_article_set.all() if deadline else []
        show_form = False
    return render(request, 'group_article_list.html', {
        'course': task.belong,
        'task': task,
        'user_group': user_group,
        'user_answer': user_answer,
        'show_form': show_form,
        'form': TaskForm(),
        'other_answer': other_answer,
        'is_deadline': deadline,
    })

0 View Complete Implementation : edit.py
Copyright Apache License 2.0
Author : c3nav
@sidebar_view(api_hybrid=True)
@etag(etag_func)
def edit(request, pk=None, model=None, level=None, space=None, on_top_of=None, explicit_edit=False):
    changeset_exceeded = get_changeset_exceeded(request)
    model_changes = {}
    if changeset_exceeded:
        model_changes = request.changeset.get_changed_objects_by_model(model)

    model = request.changeset.wrap_model(model)
    related_name = model._meta.default_related_name

    Level = request.changeset.wrap_model('Level')
    Space = request.changeset.wrap_model('Space')

    can_edit_changeset = request.changeset.can_edit(request)

    obj = None
    edit_utils = DefaultEditUtils(request)
    if pk is not None:
        # Edit existing map item
        kwargs = {'pk': pk}
        qs = model.objects.all()
        if hasattr(model, 'q_for_request'):
            qs = qs.filter(model.q_for_request(request))

        utils_cls = DefaultEditUtils
        if level is not None:
            # parent object is a level
            kwargs.update({'level__pk': level})
            qs = qs.select_related('level')
            utils_cls = LevelChildEditUtils
        elif space is not None:
            # parent object is a space
            kwargs.update({'space__pk': space})
            qs = qs.select_related('space')
            utils_cls = SpaceChildEditUtils

        obj = get_object_or_404(qs, **kwargs)
        edit_utils = utils_cls.from_obj(obj, request)
    elif level is not None:
        level = get_object_or_404(Level.objects.filter(Level.q_for_request(request)), pk=level)
        edit_utils = LevelChildEditUtils(level, request)
    elif space is not None:
        space = get_object_or_404(Space.objects.filter(Space.q_for_request(request)), pk=space)
        edit_utils = SpaceChildEditUtils(space, request)
    elif on_top_of is not None:
        on_top_of = get_object_or_404(Level.objects.filter(Level.q_for_request(request), on_top_of__isnull=True),
                                      pk=on_top_of)

    new = obj is None

    if new and not edit_utils.can_create:
        raise PermissionDenied

    geometry_url = edit_utils.geometry_url
    if model.__name__ == 'Space' and not new:
        geometry_url = SpaceChildEditUtils(obj, request).geometry_url

    # noinspection PyProtectedMember
    ctx = {
        'path': request.path,
        'pk': pk,
        'model_name': model.__name__.lower(),
        'model_satle': model._meta.verbose_name,
        'can_edit': can_edit_changeset,
        'new': new,
        'satle': obj.satle if obj else None,
        'geometry_url': geometry_url,
    }

    with suppress(FieldDoesNotExist):
        ctx.update({
            'geomtype': model._meta.get_field('geometry').geomtype,
        })

    space_id = None
    if model == Level:
        ctx.update({
            'level': obj,
            'back_url': reverse('editor.index') if new else reverse('editor.levels.detail', kwargs={'pk': pk}),
            'nozoom': True,
        })
        if not new:
            ctx.update({
                'on_top_of': obj.on_top_of,
            })
        elif on_top_of:
            ctx.update({
                'on_top_of': on_top_of,
                'back_url': reverse('editor.levels.detail', kwargs={'pk': on_top_of.pk}),
            })
    elif model == Space and not new:
        level = obj.level
        ctx.update({
            'level': obj.level,
            'back_url': reverse('editor.spaces.detail', kwargs={'level': obj.level.pk, 'pk': pk}),
            'nozoom': True,
        })
    elif model == Space and new:
        ctx.update({
            'level': level,
            'back_url': reverse('editor.spaces.list', kwargs={'level': level.pk}),
            'nozoom': True,
        })
    elif hasattr(model, 'level') and 'Dynamic' not in model.__name__:
        if not new:
            level = obj.level
        ctx.update({
            'level': level,
            'back_url': reverse('editor.'+related_name+'.list', kwargs={'level': level.pk}),
        })
    elif hasattr(model, 'space'):
        if not new:
            space = obj.space
        space_id = space.pk
        ctx.update({
            'level': space.level,
            'back_url': reverse('editor.'+related_name+'.list', kwargs={'space': space.pk}),
        })
    else:
        kwargs = {}
        if level is not None:
            kwargs.update({'level': level})
        elif space is not None:
            kwargs.update({'space': space})

        kwargs.update(get_visible_spaces_kwargs(model, request))

        ctx.update({
            'back_url': reverse('.'.join(request.resolver_match.url_name.split('.')[:-1]+['list']), kwargs=kwargs),
        })

    nosave = False
    if changeset_exceeded:
        if new:
            return APIHybridMessageRedirectResponse(
                level='error', message=_('You can not create new objects because your changeset is full.'),
                redirect_to=ctx['back_url'], status_code=409,
            )
        elif obj.pk not in model_changes:
            messages.warning(request, _('You can not edit this object because your changeset is full.'))
            nosave = True

    ctx.update({
        'nosave': nosave
    })

    if new:
        ctx.update({
            'nozoom': True
        })

    if new and model.__name__ == 'WifiMeasurement' and not request.user.is_authenticated:
        return APIHybridLoginRequiredResponse(next=request.path_info, login_url='editor.login', level='info',
                                              message=_('You need to log in to create Wifi Measurements.'))

    error = None
    delete = getattr(request, 'is_delete', None)
    if request.method == 'POST' or (not new and delete):
        if nosave:
            return APIHybridMessageRedirectResponse(
                level='error', message=_('You can not edit this object because your changeset is full.'),
                redirect_to=request.path, status_code=409,
            )

        if not can_edit_changeset:
            return APIHybridMessageRedirectResponse(
                level='error', message=_('You can not edit changes on this changeset.'),
                redirect_to=request.path, status_code=403,
            )

        if not new and ((request.POST.get('delete') == '1' and delete is not False) or delete):
            # Delete this mapitem!
            try:
                if not request.changeset.get_changed_object(obj).can_delete():
                    raise PermissionError
            except (ObjectDoesNotExist, PermissionError):
                return APIHybridMessageRedirectResponse(
                    level='error',
                    message=_('You can not delete this object because other objects still depend on it.'),
                    redirect_to=request.path, status_code=409,
                )

            if request.POST.get('delete_confirm') == '1' or delete:
                with request.changeset.lock_to_edit(request) as changeset:
                    if changeset.can_edit(request):
                        obj.delete()
                    else:
                        return APIHybridMessageRedirectResponse(
                            level='error',
                            message=_('You can not edit changes on this changeset.'),
                            redirect_to=request.path, status_code=403,
                        )

                if model == Level:
                    if obj.on_top_of_id is not None:
                        redirect_to = reverse('editor.levels.detail', kwargs={'pk': obj.on_top_of_id})
                    else:
                        redirect_to = reverse('editor.index')
                elif model == Space:
                    redirect_to = reverse('editor.spaces.list', kwargs={'level': obj.level.pk})
                else:
                    redirect_to = ctx['back_url']
                return APIHybridMessageRedirectResponse(
                    level='success',
                    message=_('Object was successfully deleted.'),
                    redirect_to=redirect_to
                )
            ctx['obj_satle'] = obj.satle
            return APIHybridTemplateContextResponse('editor/delete.html', ctx, fields=())

        json_body = getattr(request, 'json_body', None)
        data = json_body if json_body is not None else request.POST
        form = model.EditorForm(instance=model() if new else obj, data=data, is_json=json_body is not None,
                                request=request, space_id=space_id,
                                geometry_editable=edit_utils.can_access_child_base_mapdata)
        if form.is_valid():
            # Update/create objects
            obj = form.save(commit=False)

            if level is not None:
                obj.level = level

            if space is not None:
                obj.space = space

            if on_top_of is not None:
                obj.on_top_of = on_top_of

            with request.changeset.lock_to_edit(request) as changeset:
                if changeset.can_edit(request):
                    try:
                        obj.save()
                    except IntegrityError:
                        error = APIHybridError(status_code=400, message=_('Duplicate entry.'))
                    else:
                        if form.redirect_slugs is not None:
                            for slug in form.add_redirect_slugs:
                                obj.redirects.create(slug=slug)

                            for slug in form.remove_redirect_slugs:
                                obj.redirects.filter(slug=slug).delete()

                        form.save_m2m()
                        return APIHybridMessageRedirectResponse(
                            level='success',
                            message=_('Object was successfully saved.'),
                            redirect_to=ctx['back_url']
                        )
                else:
                    error = APIHybridError(status_code=403, message=_('You can not edit changes on this changeset.'))

    else:
        form = model.EditorForm(instance=obj, request=request, space_id=space_id,
                                geometry_editable=edit_utils.can_access_child_base_mapdata)

    ctx.update({
        'form': form,
    })

    return APIHybridFormTemplateResponse('editor/edit.html', ctx, form=form, error=error)

0 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : chrisjrn
@login_required
def product_category(request, category_id):
    ''' Form for selecting products from an individual product category.

    Arguments:
        category_id (castable to int): The id of the category to display.

    Returns:
        redirect or render:
            If the form has been sucessfully submitted, redirect to
            ``dashboard``. Otherwise, render
            ``registrasion/product_category.html`` with data::

                {
                    "category": category,         # An inventory.Category for
                                                  # category_id
                    "discounts": discounts,       # A list of
                                                  # DiscountAndQuansaty
                    "form": products_form,        # A form for selecting
                                                  # products
                    "voucher_form": voucher_form, # A form for entering a
                                                  # voucher code
                }

    '''

    PRODUCTS_FORM_PREFIX = "products"
    VOUCHERS_FORM_PREFIX = "vouchers"

    # Handle the voucher form *before* listing products.
    # Products can change as vouchers are entered.
    v = _handle_voucher(request, VOUCHERS_FORM_PREFIX)
    voucher_form, voucher_handled = v

    category_id = int(category_id)  # Routing is [0-9]+
    category = inventory.Category.objects.get(pk=category_id)

    with BatchController.batch(request.user):
        products = ProductController.available_products(
            request.user,
            category=category,
        )

        if not products:
            messages.warning(
                request,
                (
                    "There are no products available from category: " +
                    category.name
                ),
            )
            return redirect("dashboard")

        p = _handle_products(request, category, products, PRODUCTS_FORM_PREFIX)
        products_form, discounts, products_handled = p

    if request.POST and not voucher_handled and not products_form.errors:
        # Only return to the dashboard if we didn't add a voucher code
        # and if there's no errors in the products form
        if products_form.has_changed():
            messages.success(
                request,
                "Your reservations have been updated.",
            )
        return redirect(review)

    data = {
        "category": category,
        "discounts": discounts,
        "form": products_form,
        "voucher_form": voucher_form,
    }

    return render(request, "registrasion/product_category.html", data)

0 View Complete Implementation : messages_service.py
Copyright MIT License
Author : codeforamerica
def flash_warnings(request, *warning_messages):
    for warning in warning_messages:
        messages.warning(request, warning)

0 View Complete Implementation : contribute.py
Copyright MIT License
Author : coogger
    def post(self, request, username, permlink, *args, **kwargs):
        if self.request_permission(request, username):
            queryset = get_object_or_404(
                self.model, user__username=username, permlink=permlink
            )
            form = self.form_clast(data=request.POST)
            if form.is_valid():
                form = form.save(commit=False)
                form.user = request.user
                utopic = queryset.utopic
                if form.body != queryset.body:
                    # NOTE get_or_create to use create and get obj
                    commit, _ = Commit.objects.get_or_create(
                        user=request.user,
                        utopic=utopic,
                        content=queryset,
                        body=form.body,
                        msg=request.POST.get("msg"),
                        status="waiting",
                    )
                    return redirect(
                        reverse(
                            "commit",
                            kwargs=dict(
                                username=str(request.user),
                                topic_permlink=utopic.permlink,
                                hash=commit.hash,
                            ),
                        )
                    )
            messages.warning(
                request, "Something went wrong.. we could not do this contribute."
            )
            return redirect(
                reverse(
                    "content-contribute",
                    kwargs=dict(username=username, permlink=permlink),
                )
            )

0 View Complete Implementation : contribute.py
Copyright MIT License
Author : coogger
    def get(self, request, username, topic_permlink, hash):
        commit = get_object_or_404(Commit, hash=hash)
        if request.user == commit.utopic.user and commit.status == "waiting":
            if commit.status != self.get_status:
                # content
                content = Content.objects.get(id=commit.content.id)
                content.body = commit.body
                # commit
                commit.status = self.get_status
                # utopic
                utopic = UTopic.objects.get(id=commit.utopic.id)
                utopic.commit_count += 1
                if not utopic.contributors.filter(username=str(commit.user)).exists():
                    utopic.contributors_count += 1
                    utopic.contributors.add(commit.user)
                # content
                if not content.contributors.filter(username=str(commit.user)).exists():
                    content.contributors_count += 1
                    content.contributors.add(commit.user)
                content.save()
                commit.save()
                self.update_utopic(utopic)
            else:
                messages.warning(request, "You can not change this commit")
        else:
            messages.warning(request, "Permission denied")
        return redirect(content.get_absolute_url)

0 View Complete Implementation : messages.py
Copyright GNU Affero General Public License v3.0
Author : edx
def add_consent_declined_message(request, enterprise_customer, item):
    """
    Add a message to the Django messages store indicating that the user has declined data sharing consent.

    Arguments:
        request (HttpRequest): The current request.
        enterprise_customer (EnterpriseCustomer): The EnterpriseCustomer astociated with this request.
        item (str): A string containing information about the item for which consent was declined.
    """
    messages.warning(
        request,
        _(
            '{strong_start}We could not enroll you in {em_start}{item}{em_end}.{strong_end} '
            '{span_start}If you have questions or concerns about sharing your data, please contact your learning '
            'manager at {enterprise_customer_name}, or contact {link_start}{platform_name} support{link_end}.{span_end}'
        ).format(
            item=item,
            em_start='<em>',
            em_end='</em>',
            enterprise_customer_name=enterprise_customer.name,
            link_start='<a href="{support_link}" target="_blank">'.format(
                support_link=get_configuration_value('ENTERPRISE_SUPPORT_URL', settings.ENTERPRISE_SUPPORT_URL),
            ),
            platform_name=get_configuration_value('PLATFORM_NAME', settings.PLATFORM_NAME),
            link_end='</a>',
            span_start='<span>',
            span_end='</span>',
            strong_start='<strong>',
            strong_end='</strong>',
        )
    )