Python django.contrib.messages.info() Examples

The following are 30 code examples of django.contrib.messages.info(). 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: order.py    From Servo with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def remove_product(request, pk, item_id):
    order = get_object_or_404(Order, pk=pk)

    # The following is to help those who hit Back after removing a product
    try:
        item = ServiceOrderItem.objects.get(pk=item_id)
    except ServiceOrderItem.DoesNotExist:
        messages.error(request, _("Order item does not exist"))
        return redirect(order)

    if request.method == 'POST':
        msg = order.remove_product(item, request.user)
        messages.info(request, msg)
        return redirect(order)

    return render(request, 'orders/remove_product.html', locals()) 
Example #2
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def project_edit_schedule(request, id):
    schedule = get_object_or_404(
        Schedule, pk=id)
    if request.method == 'POST':
        form = ScheduleForm(data=request.POST, instance=schedule, request=request)
        if form.is_valid():
            form.save()
            xf = int(form.cleaned_data.get('form', 0))
            if xf:
                if FieldSightXF.objects.filter(project=schedule.project, schedule=schedule, is_scheduled=True).exists():
                    fs_xform = FieldSightXF.objects.get(project=schedule.project, schedule=schedule, is_scheduled=True)
                    if fs_xform.xf.id != xf:
                        fs_xform.xf_id = xf
                        fs_xform.save()
                else:
                    FieldSightXF.objects.create(
                        xf_id=xf, is_scheduled=True,schedule=schedule,project=schedule.project, is_deployed=True)
            messages.info(request, 'Schedule {} Saved.'.format(schedule.name))
            return HttpResponseRedirect(reverse("forms:project-survey", kwargs={'project_id': schedule.project.id}))
    form = ScheduleForm(instance=schedule, request=request)
    if FieldSightXF.objects.filter(schedule=schedule).exists():
        if FieldSightXF.objects.get(schedule=schedule).xf:
            form.fields['form'].initial= FieldSightXF.objects.get(schedule=schedule).xf.id
    return render(request, "fsforms/schedule_form.html",
                  {'form': form, 'obj': schedule.project, 'is_project':True, 'is_general':False, 'is_edit':True}) 
Example #3
Source File: oauth_api.py    From civet with Apache License 2.0 6 votes vote down vote up
def callback(self, request):
        """
        This is the callback that will be called after the user
        authorizes.
        """
        try:
            self.fetch_token(request)
            if self._token_key in request.session:
                oauth_session = self.start_session(request.session)
                response = oauth_session.get(self._user_url)
                response.raise_for_status()
                request.session[self._user_key] = self.get_json_value(response, self._callback_user_key)
                self.update_user(request.session)
                msg = '%s logged in on %s' % (request.session[self._user_key], self._hostname)
                messages.info(request, msg)
                logger.info(msg)
            else:
                messages.error(request, "Couldn't get token when trying to log in")
        except Exception as e:
            msg = "Error when logging in : %s" % e
            logger.info(msg)
            messages.error(request, msg)
            self.sign_out(request)

        return self.do_redirect(request) 
Example #4
Source File: oauth_api.py    From civet with Apache License 2.0 6 votes vote down vote up
def sign_in(self, request):
        """
        Endpoint for the user signing in. Will start
        the OAuth2 authentication process.
        After this step the user will be redirected
        to the server sign in page. After that, the server
        will automatically call our registered callback,
        which is "callback" above.
        That will get access to the token that will be
        used in all future communications.
        """
        token = request.session.get(self._token_key)
        request.session['source_url'] = request.GET.get('next', None)
        if token:
            messages.info(request, "Already signed in on %s" % self._hostname)
            return self.do_redirect(request)

        oauth_session = OAuth2Session(self._client_id, scope=self._scope, redirect_uri=self._redirect_uri)
        authorization_url, state = oauth_session.authorization_url(self._auth_url)
        request.session[self._state_key] = state
        # Get rid of these keys on login
        for key in self._addition_keys:
            request.session.pop(key, None)
        return redirect(authorization_url) 
Example #5
Source File: views.py    From pasportaservo with GNU Affero General Public License v3.0 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        user = get_object_or_404(User, pk=kwargs['pk'])
        if user.pk != request.user.pk:
            raise Http404("Only user the token was created for can use this view.")
        old_email, new_email = user.email, kwargs['email']
        user.email = new_email
        user.save()
        if kwargs.get('verification'):
            messages.info(request, _("Your email address has been successfully verified!"), extra_tags='eminent')
        else:
            messages.info(request, _("Your email address has been successfully updated!"), extra_tags='eminent')
        try:
            if user.profile.email == old_email:  # Keep profile email in sync
                user.profile.email = new_email
                user.profile.save()
        except Profile.DoesNotExist:
            return HttpResponseRedirect(reverse_lazy('profile_create'))
        else:
            return HttpResponseRedirect(reverse_lazy('profile_settings', kwargs={
                'pk': user.profile.pk, 'slug': user.profile.autoslug})) 
Example #6
Source File: views.py    From peering-manager with Apache License 2.0 6 votes vote down vote up
def get(self, request, slug):
        internet_exchange = get_object_or_404(InternetExchange, slug=slug)

        # Check if the PeeringDB ID is valid
        if not internet_exchange.is_peeringdb_valid():
            # If not, try to fix it automatically
            peeringdb_id = internet_exchange.get_peeringdb_id()
            if peeringdb_id != 0:
                internet_exchange.peeringdb_id = peeringdb_id
                internet_exchange.save()
                messages.info(
                    request,
                    "The PeeringDB record reference for this IX was invalid, it has been fixed.",
                )

        context = {"internet_exchange": internet_exchange}
        return render(request, "peering/ix/details.html", context) 
Example #7
Source File: release.py    From DCRM with GNU Affero General Public License v3.0 6 votes vote down vote up
def set_default_view(request, release_id):
    """
    :param release_id: The release
    :param request: Django Request
    :return: Redirect Response
    """
    release_instance = Release.objects.get(id=release_id)
    
    messages.info(request, mark_safe(_(
        "Active release \"<a href=\"%(release_url)s\">%(release)s</a>\" has been set.").format(
            release_url=release_instance.get_admin_url(),
            release=str(release_instance)
        )
    ))
    
    setting_instance = Setting.objects.get()
    setting_instance.active_release = release_instance
    setting_instance.save()
    
    return redirect(setting_instance.get_admin_url()) 
Example #8
Source File: oauth_api.py    From civet with Apache License 2.0 6 votes vote down vote up
def sign_out(self, request):
        """
        Just removes all the server specific
        entries in the user's session.
        """
        user = request.session.get(self._user_key, None)
        if user:
            msg = 'Logged out "%s" on %s' % (user, self._hostname)
            messages.info(request, msg)
            logger.info(msg)

        for key in list(request.session.keys()):
            if key.startswith(self._prefix):
                request.session.pop(key, None)

        # Get rid of these keys on logout
        for key in self._addition_keys:
            request.session.pop(key, None)

        request.session.modified = True
        return self.do_redirect(request) 
Example #9
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def fill_form_type(request, pk=None):
    field_sight_form = get_object_or_404(
        FieldSightXF, pk=pk)
    if request.method == 'POST':
        form = FormTypeForm(request.POST)
        if form.is_valid():
            form_type = form.cleaned_data.get('form_type', '3')
            form_type = int(form_type)
            messages.info(request, 'Form Type Saved.')
            if form_type == 3:
                return HttpResponseRedirect(reverse("forms:library-forms-list"))
            elif form_type == 2:
                field_sight_form.is_scheduled = True
                field_sight_form.save()
                return HttpResponseRedirect(reverse("forms:fill_details_schedule", kwargs={'pk': field_sight_form.id}))
            else:
                field_sight_form.is_staged = True
                field_sight_form.save()
                return HttpResponseRedirect(reverse("forms:fill_details_stage", kwargs={'pk': field_sight_form.id}))
    else:
        form = FormTypeForm()
    return render(request, "fsforms/stage_or_schedule.html", {'form': form, 'obj': field_sight_form}) 
Example #10
Source File: views.py    From civet with Apache License 2.0 6 votes vote down vote up
def get_job_results(request, job_id):
    """
    Just download all the output of the job into a tarball.
    """
    job = get_object_or_404(models.Job.objects.select_related('recipe',).prefetch_related('step_results'), pk=job_id)
    perms = Permissions.job_permissions(request.session, job)
    if not perms['can_see_results']:
        return HttpResponseForbidden('Not allowed to see results')

    response = HttpResponse(content_type='application/x-gzip')
    base_name = 'results_{}_{}'.format(job.pk, get_valid_filename(job.recipe.name))
    response['Content-Disposition'] = 'attachment; filename="{}.tar.gz"'.format(base_name)
    tar = tarfile.open(fileobj=response, mode='w:gz')
    for result in job.step_results.all():
        info = tarfile.TarInfo(name='{}/{:02}_{}'.format(base_name, result.position, get_valid_filename(result.name)))
        s = BytesIO(result.plain_output().replace('\u2018', "'").replace("\u2019", "'").encode("utf-8", "replace"))
        buf = s.getvalue()
        info.size = len(buf)
        info.mtime = time.time()
        tar.addfile(tarinfo=info, fileobj=s)
    tar.close()
    return response 
Example #11
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def edit_faculty_member_info(request, userid):
    person, _ = _get_faculty_or_404(request.units, userid)

    info = (FacultyMemberInfo.objects.filter(person=person).first()
            or FacultyMemberInfo(person=person))

    if request.POST:
        form = FacultyMemberInfoForm(request.POST, instance=info)

        if form.is_valid():
            new_info = form.save()
            person.set_title(new_info.title)
            person.save()
            messages.success(request, 'Contact information was saved successfully.')
            return HttpResponseRedirect(new_info.get_absolute_url())
    else:
        form = FacultyMemberInfoForm(instance=info)

    context = {
        'person': person,
        'form': form,
    }
    return render(request, 'faculty/edit_faculty_member_info.html', context) 
Example #12
Source File: views.py    From tom_base with GNU General Public License v3.0 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        """
        Method that handles the GET requests for this view. Calls the management command to update the reduced data and
        adds a hint using the messages framework about automation.
        """
        target_id = request.GET.get('target_id', None)
        out = StringIO()
        if target_id:
            call_command('updatereduceddata', target_id=target_id, stdout=out)
        else:
            call_command('updatereduceddata', stdout=out)
        messages.info(request, out.getvalue())
        add_hint(request, mark_safe(
                          'Did you know updating observation statuses can be automated? Learn how in '
                          '<a href=https://tom-toolkit.readthedocs.io/en/stable/customization/automation.html>'
                          'the docs.</a>'))
        return HttpResponseRedirect(self.get_redirect_url(*args, **kwargs)) 
Example #13
Source File: mixins.py    From django-idcops with Apache License 2.0 6 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super(BaseRequiredMixin, self).get_context_data(**kwargs)
        self.meta = {}
        try:
            self.meta['logo'] = self.request.user.onidc.name
            self.meta['icon'] = self.opts.icon
            self.meta['model_name'] = self.model_name
            self.meta['verbose_name'] = self.verbose_name
            self.meta['title'] = "{} {}".format(self.verbose_name, self.title)
        except BaseException:
            self.meta['title'] = self.title
        context['meta'] = self.meta
        context['menus'] = system_menus
        # construct_menus()
        # from django import db
        # logger.info('queries count: {}'.format(len(db.connection.queries)))
        return context 
Example #14
Source File: views.py    From lmgtdfy with MIT License 6 votes vote down vote up
def form_valid(self, form):
        data = form.cleaned_data
        domain = data['domain_base']
        domain_is_whitelisted = check_valid_tld(domain)
        if not domain_is_whitelisted:
            messages.info(
                self.request,
                "Sorry, but to limit the cost of running this service, we have not enabled searching this domain name (%s)." % domain
            )
            return HttpResponseRedirect(resolve_url('home'))

        search_done = search_bing(domain)
        if not search_done:
            messages.info(
                self.request,
                "This domain has already been requested today! Here is what we've gathered."
            )
        else:
            messages.info(
                self.request,
                "Gathering results now. They will be displayed shortly."
            )
        return HttpResponseRedirect(
            resolve_url('domain_result', domain)
        ) 
Example #15
Source File: views.py    From lmgtdfy with MIT License 6 votes vote down vote up
def get_context_data(self, **kwargs):
        context                = super(SearchResultView, self).get_context_data(**kwargs)
        domain_name            = self.kwargs['domain']
        context['domain_name'] = domain_name
        context['format']      = self.kwargs.get('fmt')
        self.kwargs['fmt']     = None # clear the format
        # so that we get a list of all of the formats for the domain
        qs = set(self.get_queryset().values_list('fmt', flat=True))
        context['file_formats'] = list(qs)
        domain = Domain.objects.filter(name=domain_name)
        search_being_performed = len(DomainSearch.objects.filter(domain=domain, completed_at=None)) > 0
        if search_being_performed:
            messages.info( 
                self.request, 
                "We're gathering more results right now. This page will refresh in 10 seconds."
            )
            context['refresh_counter'] = 10
        return context 
Example #16
Source File: views.py    From tom_base with GNU General Public License v3.0 6 votes vote down vote up
def form_valid(self, form):
        """
        Runs after form validation. Creates the ``Target``, and creates any ``TargetName`` or ``TargetExtra`` objects,
        then runs the ``target_post_save`` hook and redirects to the success URL.

        :param form: Form data for target creation
        :type form: subclass of TargetCreateForm
        """
        super().form_valid(form)
        extra = TargetExtraFormset(self.request.POST)
        names = TargetNamesFormset(self.request.POST)
        if extra.is_valid() and names.is_valid():
            extra.instance = self.object
            extra.save()
            names.instance = self.object
            names.save()
        else:
            form.add_error(None, extra.errors)
            form.add_error(None, extra.non_form_errors())
            form.add_error(None, names.errors)
            form.add_error(None, names.non_form_errors())
            return super().form_invalid(form)
        logger.info('Target post save hook: %s created: %s', self.object, True)
        run_hook('target_post_save', target=self.object, created=True)
        return redirect(self.get_success_url()) 
Example #17
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def add_sub_stage(request, pk=None):
    stage = get_object_or_404(
        Stage, pk=pk)
    if request.method == 'POST':
        form = AddSubSTageForm(data=request.POST, request=request)
        if form.is_valid():
            child_stage = form.save(commit=False)
            child_stage.stage = stage
            child_stage.project = stage.project
            child_stage.site = stage.site
            child_stage.group = stage.group
            child_stage.save()
            form = int(form.cleaned_data.get('form',0))
            if form:
                if stage.site:
                    FieldSightXF.objects.create(xf_id=form, is_staged=True, stage=child_stage,site=stage.site)
                else:
                    FieldSightXF.objects.create(xf_id=form, is_staged=True, stage=child_stage,project=stage.project)
            messages.info(request, 'Sub Stage {} Saved.'.format(child_stage.name))
            return HttpResponseRedirect(reverse("forms:stages-detail", kwargs={'pk': stage.id}))
    order = Stage.objects.filter(stage=stage).count() + 1
    instance = Stage(name="Sub Stage"+str(order), order=order)
    form = AddSubSTageForm(instance=instance, request=request)
    return render(request, "fsforms/add_sub_stage.html", {'form': form, 'obj': stage}) 
Example #18
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def deploy_stages(request, id):
    project = Project(pk=id)
    sites = project.sites.all()
    main_stages = project.stages.filter(stage__isnull=True)
    with transaction.atomic():
        Stage.objects.filter(site__project=project).delete()
        FieldSightXF.objects.filter(is_staged=True, site__project=project).delete()
        for main_stage in main_stages:
            for site in sites:
                send_message_stages(site)
                site_main_stage = Stage(name=main_stage.name, order=main_stage.order, site=site,
                                   description=main_stage.description)
                site_main_stage.save()
                project_sub_stages = Stage.objects.filter(stage__id=main_stage.pk)
                for project_sub_stage in project_sub_stages:
                    site_sub_stage = Stage(name=project_sub_stage.name, order=project_sub_stage.order, site=site,
                                   description=project_sub_stage.description, stage=site_main_stage)
                    site_sub_stage.save()
                    if FieldSightXF.objects.filter(stage=project_sub_stage).exists():
                        fsxf = FieldSightXF.objects.filter(stage=project_sub_stage)[0]
                        FieldSightXF.objects.get_or_create(is_staged=True, xf=fsxf.xf, site=site,
                                                           fsform=fsxf, stage=site_sub_stage, is_deployed=True)

    messages.info(request, 'Stages Form Deployed to Sites')
    return HttpResponseRedirect(reverse("forms:setup-project-stages", kwargs={'id': id})) 
Example #19
Source File: profile_views.py    From fermentrack with MIT License 6 votes vote down vote up
def profile_undelete(request, profile_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.edit_fermentation_profile'):
    #     messages.error(request, 'Your account is not permissioned to edit fermentation profiles. Please contact an admin')
    #     return redirect("/")
    try:
        this_profile = FermentationProfile.objects.get(id=profile_id)
    except:
        # The URL contained an invalid profile ID. Redirect to the profile
        # list.
        messages.error(request, 'Invalid profile selected to save from deletion')
        return redirect('profile_list')

    if this_profile.status == FermentationProfile.STATUS_PENDING_DELETE:
        this_profile.status = FermentationProfile.STATUS_ACTIVE
        this_profile.save()
        messages.success(request,
                         'Profile \'{}\' has been removed from the queue for deletion.'.format(this_profile.name))
    else:
        messages.info(request, 'Profile \'{}\' was not previously queued for deletion and has not been updated.'.format(this_profile.name))

    return redirect('profile_list') 
Example #20
Source File: profile_views.py    From fermentrack with MIT License 6 votes vote down vote up
def profile_delete(request, profile_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.edit_fermentation_profile'):
    #     messages.error(request, 'Your account is not permissioned to edit fermentation profiles. Please contact an admin')
    #     return redirect("/")
    try:
        this_profile = FermentationProfile.objects.get(id=profile_id)
    except:
        # The URL contained an invalid profile ID. Redirect to the profile
        # list.
        messages.error(request, 'Invalid profile selected for deletion')
        return redirect('profile_list')

    if not this_profile.is_editable():
        # Due to the way we're implementing fermentation profiles, we don't want any edits to a profile that is
        # currently in use.
        this_profile.status = FermentationProfile.STATUS_PENDING_DELETE
        this_profile.save()
        messages.info(request,
                      'Profile \'{}\' is currently in use but has been queued for deletion.'.format(this_profile.name))
    else:
        this_profile.delete()
        messages.success(request, 'Profile \'{}\' was not in use, and has been deleted.'.format(this_profile.name))

    return redirect('profile_list') 
Example #21
Source File: views.py    From BikeMaps with MIT License 6 votes vote down vote up
def profile(request):
    user = get_object_or_404(User, username=request.user)

    if request.method == 'POST':
        form = UserProfileForm(data=request.POST, instance=user)

        if form.is_valid():
            form.save(commit=False)
            user.save()
            messages.info(request, _("Information updated."))
            form = UserProfileForm(instance=user)

    else:
        form = UserProfileForm(instance=user)

    return render(request, "userApp/profile.html", {'user': user, 'form': form}) 
Example #22
Source File: views.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self, request, slug):
        contention = self.get_object()
        contention.is_published = True
        contention.save()
        messages.info(request, u"Argument is published now.")
        return redirect(contention) 
Example #23
Source File: views.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def post(self, request):
        form = LoginForm(request, data=request.POST)

        if form.is_valid():
            # Check where should the user be redirected
            next_redirect = request.POST.get("next", "")
            if not is_safe_url(url=next_redirect, allowed_hosts=[request.get_host()]):
                next_redirect = reverse("home")

            auth_login(request, form.get_user())
            messages.info(request, "Logged in as {}.".format(request.user))
            return HttpResponseRedirect(next_redirect)

        return render(request, self.template, {"form": form}) 
Example #24
Source File: views.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def get(self, request):
        if is_user_logged_in(request):
            auth_logout(request)
            messages.info(request, "You have logged out.")

        return redirect("home") 
Example #25
Source File: views.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def get(self, request):
        """
        Method used to render the view when form is not submitted.
        """
        objects = self.get_objects()
        formset = None

        if len(objects) > 0:
            if not self.custom_formset:
                ObjectFormSet = formset_factory(self.form_model, extra=0)
            else:
                ObjectFormSet = formset_factory(
                    self.form_model, formset=self.custom_formset, extra=0
                )
            formset = ObjectFormSet(initial=objects)
        else:
            messages.info(request, "No data to import.")
            return redirect(self.get_return_url(request))

        return render(
            request,
            self.template,
            {
                "formset": formset,
                "obj_type": self.form_model._meta.model._meta.verbose_name,
                "return_url": self.get_return_url(request),
            },
        ) 
Example #26
Source File: build.py    From DCRM with GNU Affero General Public License v3.0 5 votes vote down vote up
def save_model(self, request, obj, form, change):
        """
        Set the active release, call building procedure, and then save.
        
        :type obj: Build
        """
        setting = preferences.Setting
        obj.active_release = setting.active_release
        super(BuildAdmin, self).save_model(request, obj, form, change)
        
        if setting.active_release is not None:
            build_args = {
                "build_uuid": obj.uuid,
                "build_all": setting.downgrade_support,
                "build_p_diff": setting.enable_pdiffs,
                "build_compression": setting.packages_compression,
                "build_secure": setting.gpg_signature,
                "build_validation": setting.packages_validation,
                "build_release": obj.active_release.id,
            }
            if settings.ENABLE_REDIS is True:
                queue = django_rq.get_queue('high')
                build_job = queue.enqueue(build_procedure, build_args)
                obj.job_id = build_job.id
                messages.info(request, mark_safe(
                    _("The Build \"<a href=\"%(job_detail)s\">%(obj)s</a>\" generating job has been added to the \"<a href=\"%(jobs)s\">high</a>\" queue.").format(
                        job_detail=reverse('rq_job_detail', kwargs={
                            'queue_index': 1,
                            'job_id': build_job.id,
                        }),
                        obj=str(obj),
                        jobs=reverse('rq_jobs', args=(1, )),
                    )
                ))
            else:
                build_procedure(build_args)
                messages.info(request, _("The Build \"%s\" generating job has been finished.") % str(obj))
            obj.save() 
Example #27
Source File: middleware.py    From casepro with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def process_view(self, request, view_func, view_args, view_kwargs):
        if request.user.is_anonymous or not request.user.has_profile():
            return

        if request.user.profile.change_password:
            url_name = request.resolver_match.url_name

            if url_name not in ALLOW_NO_CHANGE:
                messages.info(request, _("You are required to change your password"))
                return HttpResponseRedirect(reverse("profiles.user_self")) 
Example #28
Source File: views.py    From arguman.org with GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self, request, slug):
        contention = self.get_object()
        contention.is_published = False
        contention.save()
        messages.info(request, u"Argüman yayından kaldırıldı.")
        return redirect(contention) 
Example #29
Source File: version.py    From DCRM with GNU Affero General Public License v3.0 5 votes vote down vote up
def save_model(self, request, obj, form, change):
        # field update
        """
        :param change: Boolean
        :param form: VersionForm
        :type obj: Version
        """
        # hash update
        obj.update_hash()
        super(VersionAdmin, self).save_model(request, obj, form, change)
        
        """
        Remove all excluded column (which are not in standard debian control part)
        to determine whether the related .deb file on file system should be updated.
        """
        excluded_column = ['enabled', 'created_at', 'os_compatibility', 'device_compatibility',
                           'update_logs', 'storage', 'online_icon', 'gallery', 'c_md5', 'c_sha1', 'c_sha256', 'c_sha512',
                           'c_size', 'download_times', 'rich_description']
        change_list = form.changed_data
        change_num = len(change_list)
        for change_var in change_list:
            if change_var in excluded_column:
                change_num -= 1
        if change is True and change_num > 0:
            update_job = obj.update_storage()
            if settings.ENABLE_REDIS is True and update_job is not None:
                messages.info(request, mark_safe(_("The Version \"<a href=\"%(job_detail)s\">%(obj)s</a>\" storage updating job has been added to the \"<a href=\"%(jobs)s\">high</a>\" queue.").format(
                        job_detail=reverse('rq_job_detail', kwargs={
                            'queue_index': 1,
                            'job_id': update_job.id,
                        }),
                        obj=str(obj),
                        jobs=reverse('rq_jobs', args=(1, ))
                    )
                ))
        else:
            pass 
Example #30
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def alter_proj_status(request, pk):
    try:
        obj = Project.objects.get(pk=int(pk))
            # alter status method on custom user
        if obj.is_active:
            obj.is_active = False
            messages.info(request, 'Project {0} Deactivated.'.format(obj.name))
        else:
            obj.is_active = True
            messages.info(request, 'Project {0} Activated.'.format(obj.name))
        obj.save()
    except:
        messages.info(request, 'Project {0} not found.'.format(obj.name))
    return HttpResponseRedirect(reverse('fieldsight:projects-list'))