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: views.py    From oxidizr with GNU General Public License v2.0 7 votes vote down vote up
def form_valid(self, form):
        base, created = BaseKeyword.objects.get_or_create(term=form.cleaned_data['term'])
        keyword = Keyword()
        keyword.base = base
        keyword.project = self.request.project
        try:
            keyword.save()
        except IntegrityError:
            # The unique_together constraint on Keyword model failed
            # TODO: Handle a more specific error, IntegrityError could be raised by things other than duplicate too
            messages.add_message(
                message=_('You already have that keyword for this project, so we did not add it again.'),
                level=messages.INFO,
                request=self.request,
                extra_tags='module-level'
            )
        return HttpResponseRedirect(self.get_success_url()) 
Example #2
Source File: views.py    From pyas2 with GNU General Public License v2.0 6 votes vote down vote up
def send_async_mdn(request, *args, **kwargs):
    """Send all pending asynchronous MDNs to all partners"""
    # Setup the python and django paths
    python_executable_path = pyas2init.gsettings['python_path']
    managepy_path = pyas2init.gsettings['managepy_path']

    # execute the django admin command "sendasyncmdn" to transfer the file to partner
    lijst = [python_executable_path, managepy_path, 'sendasyncmdn']
    pyas2init.logger.info(_(u'Send async MDNs started with parameters: "%(parameters)s"'), {'parameters': str(lijst)})
    try:
        subprocess.Popen(lijst).pid
    except Exception as msg:
        notification = _(u'Errors while trying to run send async MDNs: "%s".') % msg
        messages.add_message(request, messages.INFO, notification)
    else:
        messages.add_message(request, messages.INFO, _(u'Sending all pending asynchronous MDNs .....'))
    return HttpResponseRedirect(reverse('home')) 
Example #3
Source File: views.py    From pyas2 with GNU General Public License v2.0 6 votes vote down vote up
def retry_failed_comms(request, *args, **kwargs):
    """ Retry communications for all failed outbound messages"""
    # Setup the python and django paths
    python_executable_path = pyas2init.gsettings['python_path']
    managepy_path = pyas2init.gsettings['managepy_path']

    # execute the django admin command "retryfailedas2comms" to transfer the file to partner
    lijst = [python_executable_path, managepy_path, 'retryfailedas2comms']
    pyas2init.logger.info(_(u'Retry Failed communications started with parameters: "%(parameters)s"'),
                          {'parameters': str(lijst)})
    try:
        subprocess.Popen(lijst).pid
    except Exception as msg:
        notification = _(u'Errors while trying to retrying failed communications: "%s".') % msg
        messages.add_message(request, messages.INFO, notification)
    else:
        messages.add_message(request, messages.INFO, _(u'Retrying failed communications .....'))
    return HttpResponseRedirect(reverse('home')) 
Example #4
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def question_delete(request: HttpRequest, course_slug: str, activity_slug: str, question_id: str) -> HttpResponse:
    if request.method in ['POST', 'DELETE']:
        quiz = get_object_or_404(Quiz, activity__slug=activity_slug, activity__offering__slug=course_slug)
        if quiz.completed():
            return ForbiddenResponse(request, 'Quiz is completed. You cannot modify questions after the end of the quiz time')
        question = get_object_or_404(Question, quiz=quiz, id=question_id)
        question.status = 'D'
        question.save()
        if quiz.activity.quiz_marking():
            # configured for quiz-based marking: update that so the order matches
            quiz.configure_marking(delete_others=False)
            messages.add_message(request, messages.INFO, 'Updated marking rubric to match quiz questions.')
        messages.add_message(request, messages.SUCCESS, 'Question deleted.')
        LogEntry(userid=request.user.username, description='deleted quiz question id=%i' % (question.id,),
                 related_object=question).save()
        return redirect('offering:quiz:index', course_slug=course_slug, activity_slug=activity_slug)
    else:
        return HttpError(request, status=405, title="Method Not Allowed", error='POST or DELETE requests only.') 
Example #5
Source File: admin.py    From heltour with MIT License 6 votes vote down vote up
def create_slack_channels(self, request, queryset):
        team_ids = []
        skipped = 0
        for team in queryset.select_related('season').nocache():
            if not team.season.is_active or team.season.is_completed:
                self.message_user(request,
                                  'The team season must be active and not completed in order to create channels.',
                                  messages.ERROR)
                return
            if len(team.season.tag) > 3:
                self.message_user(request, 'The team season tag is too long to create a channel.',
                                  messages.ERROR)
                return
            if team.slack_channel == '':
                team_ids.append(team.pk)
            else:
                skipped += 1
        signals.do_create_team_channel.send(sender=self, team_ids=team_ids)
        self.message_user(request, 'Creating %d channels. %d skipped.' % (len(team_ids), skipped),
                          messages.INFO)


# ------------------------------------------------------------------------------- 
Example #6
Source File: admin.py    From heltour with MIT License 6 votes vote down vote up
def verify_data(self, request, queryset):
        for season in queryset:
            # Ensure SeasonPlayer objects exist for all paired players
            if season.league.competitor_type == 'team':
                pairings = TeamPlayerPairing.objects.filter(team_pairing__round__season=season)
            else:
                pairings = LonePlayerPairing.objects.filter(round__season=season)
            for p in pairings:
                SeasonPlayer.objects.get_or_create(season=season, player=p.white)
                SeasonPlayer.objects.get_or_create(season=season, player=p.black)
            # Normalize all gamelinks
            bad_gamelinks = 0
            for p in pairings:
                old = p.game_link
                p.game_link, ok = normalize_gamelink(old)
                if not ok:
                    bad_gamelinks += 1
                if p.game_link != old:
                    p.save()
            if bad_gamelinks > 0:
                self.message_user(request,
                                  '%d bad gamelinks for %s.' % (bad_gamelinks, season.name),
                                  messages.WARNING)
        self.message_user(request, 'Data verified.', messages.INFO) 
Example #7
Source File: views.py    From hashtags with MIT License 6 votes vote down vote up
def get_queryset(self):
        form = self.form_class(self.request.GET)
        if form.is_valid():
            form_data = form.cleaned_data
            if 'wikidata.org' in form_data['project']:
                hashtag_qs = []
                messages.add_message(self.request, messages.INFO,
                # Translators: Message to be displayed when a user specify 'wikidata' in the project field.
                _('Unfortunately Wikidata searching is not currently supported.'))
            else:    
                hashtag_qs = hashtag_queryset(form_data)

                if not hashtag_qs:
                    messages.add_message(self.request, messages.INFO,
                    # Translators: Message to be displayed when there are no results for the search.
                    _('No results found.'))                     

            return hashtag_qs

        # We're mixing forms and listview; paginate_by expects to always
        # have *something* to paginate, so we send back an empty list
        # if the form hasn't been filled yet.
        return [] 
Example #8
Source File: options.py    From bioforum with MIT License 6 votes vote down vote up
def message_user(self, request, message, level=messages.INFO, extra_tags='',
                     fail_silently=False):
        """
        Send a message to the user. The default implementation
        posts a message using the django.contrib.messages backend.

        Exposes almost the same API as messages.add_message(), but accepts the
        positional arguments in a different order to maintain backwards
        compatibility. For convenience, it accepts the `level` argument as
        a string rather than the usual level number.
        """
        if not isinstance(level, int):
            # attempt to get the level if passed a string
            try:
                level = getattr(messages.constants, level.upper())
            except AttributeError:
                levels = messages.constants.DEFAULT_TAGS.values()
                levels_repr = ', '.join('`%s`' % l for l in levels)
                raise ValueError(
                    'Bad message level string: `%s`. Possible values are: %s'
                    % (level, levels_repr)
                )

        messages.add_message(request, level, message, extra_tags=extra_tags, fail_silently=fail_silently) 
Example #9
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def add_central_engineer(request, pk):
    obj = get_object_or_404(
        Project, pk=pk, is_active=True)
    group = Group.objects.get(name__exact="Reivewer")
    role_obj = UserRole(project=obj, group=group)
    scenario = 'Assign'
    if request.method == 'POST':
        form = SetProjectRoleForm(data=request.POST, instance=role_obj, request=request)
        if form.is_valid():
            role_obj = form.save(commit=False)
            user_id = request.POST.get('user')
            role_obj.user_id = int(user_id)
            role_obj.save()
        messages.add_message(request, messages.INFO, 'Reviewer Added')
        return HttpResponseRedirect(reverse("fieldsight:project-dashboard", kwargs={'pk': obj.pk}))
    else:
        form = SetProjectRoleForm(instance=role_obj, request=request,)
    return render(request, "fieldsight/add_central_engineer.html", {'obj':obj,'form':form, 'scenario':scenario}) 
Example #10
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def add_supervisor(request, pk):
    obj = get_object_or_404(
        Site, pk=int(pk), is_active=True)
    group = Group.objects.get(name__exact="Site Supervisor")
    role_obj = UserRole(site=obj, group=group)
    if request.method == 'POST':
        form = SetSupervisorForm(data=request.POST, instance=role_obj, request=request)
        if form.is_valid():
            role_obj = form.save(commit=False)
            user_id = request.POST.get('user')
            role_obj.user_id = int(user_id)
            role_obj.save()
        messages.add_message(request, messages.INFO, 'Site Supervisor Added')
        return HttpResponseRedirect(reverse("fieldsight:site-dashboard", kwargs={'pk': obj.pk}))
    else:
        form = SetSupervisorForm(instance=role_obj, request=request)
    return render(request, "fieldsight/add_supervisor.html", {'obj':obj,'form':form}) 
Example #11
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def add_proj_manager(request, pk):
    obj = get_object_or_404(
        Project, pk=pk, is_active=True)
    group = Group.objects.get(name__exact="Project Manager")
    role_obj = UserRole(project=obj, group=group)
    scenario = 'Assign'
    if request.method == 'POST':
        form = SetProjectManagerForm(data=request.POST, instance=role_obj, request=request)
        if form.is_valid():
            role_obj = form.save(commit=False)
            user_id = request.POST.get('user')
            role_obj.user_id = int(user_id)
            role_obj.save()
        messages.add_message(request, messages.INFO, 'Project Manager Added')
        return HttpResponseRedirect(reverse("fieldsight:project-dashboard", kwargs={'pk': obj.pk}))
    else:
        form = SetProjectManagerForm(instance=role_obj, request=request)
    return render(request, "fieldsight/add_project_manager.html", {'obj':obj,'form':form, 'scenario':scenario}) 
Example #12
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def stage_add_form(request, pk=None):
    stage = get_object_or_404(
        Stage, pk=pk)
    if stage.stage.site:
        instance = FieldSightXF(site=stage.stage.site, is_staged=True, is_scheduled=False, stage=stage)
        if request.method == 'POST':
            form = AssignFormToStageForm(request.POST, instance=instance)
            if form.is_valid():
                form.save()
                messages.add_message(request, messages.INFO, 'Form Assigned Successfully.')
                return HttpResponseRedirect(reverse("forms:stages-detail", kwargs={'pk': stage.stage.id}))
        else:
            form = AssignFormToStageForm(instance=instance)
        return render(request, "fsforms/stage_add_form.html", {'form': form, 'obj': stage})
    else:
        if request.method == 'POST':
            form = AssignFormToStageForm(request.POST)
            if form.is_valid():
                form.save()
                messages.add_message(request, messages.INFO, 'Form Assigned Successfully.')
                return HttpResponseRedirect(reverse("forms:stages-detail", kwargs={'pk': stage.stage.id}))
        else:
            form = AssignFormToStageForm()
        return render(request, "fsforms/stage_add_form.html", {'form': form, 'obj': stage}) 
Example #13
Source File: options.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def message_user(self, request, message, level=messages.INFO, extra_tags='',
                     fail_silently=False):
        """
        Send a message to the user. The default implementation
        posts a message using the django.contrib.messages backend.

        Exposes almost the same API as messages.add_message(), but accepts the
        positional arguments in a different order to maintain backwards
        compatibility. For convenience, it accepts the `level` argument as
        a string rather than the usual level number.
        """

        if not isinstance(level, int):
            # attempt to get the level if passed a string
            try:
                level = getattr(messages.constants, level.upper())
            except AttributeError:
                levels = messages.constants.DEFAULT_TAGS.values()
                levels_repr = ', '.join('`%s`' % l for l in levels)
                raise ValueError('Bad message level string: `%s`. '
                        'Possible values are: %s' % (level, levels_repr))

        messages.add_message(request, level, message, extra_tags=extra_tags,
                fail_silently=fail_silently) 
Example #14
Source File: views.py    From bud with MIT License 5 votes vote down vote up
def form_valid(self, form):
        messages.add_message(
            self.request, messages.INFO, _("Infos successfully updated")
        )
        return super().form_valid(form) 
Example #15
Source File: admin.py    From DeerU with GNU General Public License v3.0 5 votes vote down vote up
def make_fail(self, request, queryset):
        for q in queryset:
            q.status = CommentStatusChoices.Failed
            q.save()
            self.message_user(request, "%s 不通过" % str(q), level=messages.INFO) 
Example #16
Source File: admin.py    From DeerU with GNU General Public License v3.0 5 votes vote down vote up
def make_pass(self, request, queryset):
        for q in queryset:
            q.status = CommentStatusChoices.Passed
            q.save()
            self.message_user(request, "%s 通过" % str(q), level=messages.INFO) 
Example #17
Source File: views.py    From hashtags with MIT License 5 votes vote down vote up
def get_context_data(self, *args, **kwargs):
        # If we have any hashtags in the database, check if we appear
        # to be up-to-date.
        try:
            latest_datetime = Hashtag.objects.all().latest('timestamp').timestamp
        except Hashtag.DoesNotExist:
            latest_datetime = datetime.now(timezone.utc)
        diff = datetime.now(timezone.utc) - latest_datetime
        if diff.seconds > 3600:
            messages.add_message(self.request, messages.INFO,
            # Translators: Message to be displayed when the latest edits are not in the database.
            _('Note that the latest edits may not currently be reflected in the tool.'))

        context = super().get_context_data(**kwargs)

        # Make sure we're setting initial values in case user has
        # already submitted something.
        context['form'] = self.form_class(self.request.GET)

        hashtags = self.object_list
        if hashtags:
            context = get_hashtags_context(self.request, hashtags, context)
        else:
            # We don't need top tags if we're showing results
            top_tags = Hashtag.objects.filter(
                timestamp__gt=datetime.now() - timedelta(days=30)
            ).values_list('hashtag').annotate(
                count=Count('hashtag')).order_by('-count')[:10]
            context['top_tags'] = [x[0] for x in top_tags]

        return context 
Example #18
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def schedule_add_form(request, pk=None):
    schedule = get_object_or_404(
        Schedule, pk=pk)
    instance = FieldSightXF(site=schedule.site, is_staged=False, is_scheduled=True, schedule=schedule)
    if request.method == 'POST':
        form = AssignFormToScheduleForm(request.POST, instance=instance, request=request)
        if form.is_valid():
            form.save()
            messages.add_message(request, messages.INFO, 'Form Assigned Successfully.')
            return HttpResponseRedirect(reverse("forms:site-survey", kwargs={'site_id': schedule.site.id}))
    form = AssignFormToScheduleForm(instance=instance, request=request)
    return render(request, "fsforms/schedule_add_form.html", {'form': form, 'obj': schedule}) 
Example #19
Source File: views.py    From Python-Programming-Blueprints with MIT License 5 votes vote down vote up
def send_cart(request):
    cart = ShoppingCart.objects.get(user_id=request.user.id)

    data = _prepare_order_data(cart)

    headers = {
        'Authorization': f'Token {settings.ORDER_SERVICE_AUTHTOKEN}',
        'Content-type': 'application/json'
    }

    service_url = f'{settings.ORDER_SERVICE_BASEURL}/api/order/add/'

    response = requests.post(
        service_url,
        headers=headers,
        data=data)

    if HTTPStatus(response.status_code) is HTTPStatus.CREATED:
        request_data = json.loads(response.text)
        ShoppingCart.objects.empty(cart)
        messages.add_message(
            request,
            messages.INFO,
            ('We received your order!'
             'ORDER ID: {}').format(request_data['order_id']))
    else:
        messages.add_message(
            request,
            messages.ERROR,
            ('Unfortunately, we could not receive your order.'
             ' Try again later.'))

    return HttpResponseRedirect(reverse_lazy('user-cart')) 
Example #20
Source File: views.py    From pyas2 with GNU General Public License v2.0 5 votes vote down vote up
def resend_message(request, pk, *args, **kwargs):
    """ Function for resending an outbound message from the Message List View"""

    # Get the message to be resent
    orig_message = models.Message.objects.get(message_id=pk)
    # Setup the python and django path
    python_executable_path = pyas2init.gsettings['python_path']
    managepy_path = pyas2init.gsettings['managepy_path']

    # Copy the message payload to a temporary location
    temp = tempfile.NamedTemporaryFile(suffix='_%s' % orig_message.payload.name, delete=False)
    with open(orig_message.payload.file, 'rb+') as source:
        temp.write(source.read())

    # execute the django admin command "sendas2message" to transfer the file to partner
    lijst = [
        python_executable_path,
        managepy_path,
        'sendas2message',
        orig_message.organization.as2_name,
        orig_message.partner.as2_name,
        temp.name
    ]
    pyas2init.logger.info(_(u'Re-send message started with parameters: "%(parameters)s"'), {'parameters': str(lijst)})
    try:
        subprocess.Popen(lijst).pid
    except Exception as msg:
        notification = _(u'Errors while trying to re-send message: "%s".') % msg
        messages.add_message(request, messages.INFO, notification)
        pyas2init.logger.info(notification)
    else:
        messages.add_message(request, messages.INFO, _(u'Re-Sending the message to your partner ......'))
    return HttpResponseRedirect(reverse('home')) 
Example #21
Source File: views.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def populate(request):
#    pathway = Pathway(keggid='1234', name='Raony', genes='ABGS,SAKHA,AKJSKJ')
#    pathway.save()

    Pathway.objects.all().delete()

    pathways = kegg_rest_request('list/pathway/hsa')
    pathways = parse_pathways(pathways)
    insert_list = []
    total = len(pathways)
    
    for keggid in pathways:
        print(total)
        total = total-1
        
#        print keggid, pathways[keggid]
        pathway_data = kegg_rest_request('get/hsa%s' % (keggid))
        genes = parse_genes(pathway_data)
        print('genes')
#        print genes
        gene_list = []
        for gene in genes:
            gene_list.append(gene['symbol'])
#        print gene_list
        gene_list = ",".join(gene_list)
#        print keggid, pathways[keggid], gene_list
#        pathway_name = pathway_data.split('\n')[1].replace('NAME', '')
    
        pathway = Pathway(kegg=keggid, name=pathways[keggid], genes=gene_list)
        pathway.save()

    message = 'finish filling pathway from kegg'
    messages.add_message(request, messages.INFO, message)
    return redirect('/databases/')


# Create your views here. 
Example #22
Source File: views.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete(self, request, *args, **kwargs):
        """
        This does not actually delete the file, only the database record.  But
        that is easy to implement.
        """
        self.object = self.get_object()
        
        #username = self.object.user.username
        
        self.object.delete()
        messages.add_message(request, messages.INFO, "Group deleted with success!")
        return redirect('individuals_list') 
Example #23
Source File: views.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def populate_mongo(request, individual_id):
    individual = get_object_or_404(Individual, pk=individual_id)
    PopulateMongoVariants.delay(individual.id)
    messages.add_message(request, messages.INFO, "Your individual is being inserted at MongoDB.")

    return redirect('individuals_list') 
Example #24
Source File: views.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def annotate(request, individual_id):
    individual = get_object_or_404(Individual, pk=individual_id)
    individual.status = 'new'
    individual.n_lines = 0
    VerifyVCF.delay(individual.id)
    individual.save()
    messages.add_message(request, messages.INFO, "Your individual is being annotated.")
    return redirect('dashboard') 
Example #25
Source File: views.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete(self, request, *args, **kwargs):
        """
        This does not actually delete the file, only the database record.  But
        that is easy to implement.
        """
        self.object = self.get_object()
        individual_id = self.object.id

        if self.object.user:
            username = self.object.user.username
        else:
            username = 'public'
        
        #delete files
        if self.object.vcf_file:
            self.object.vcf_file.delete()

        # if self.object.strs_file:
        #     self.object.strs_file.delete()
        # if self.object.cnvs_file:
        #     self.object.cnvs_file.delete()
        os.system('rm -rf %s/genomes/%s/%s' % (settings.BASE_DIR, username, individual_id))

        self.object.delete()
        
        
        
        
#        response = JSONResponse(True, {}, response_mimetype(self.request))
#        response['Content-Disposition'] = 'inline; filename=files.json'
#        return response
        messages.add_message(request, messages.INFO, "Individual deleted with success!")
        #return redirect('individuals_list')
        return redirect('individuals_list') 
Example #26
Source File: views.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete(self, request, *args, **kwargs):
        """
        This does not actually delete the file, only the database record.  But
        that is easy to implement.
        """
        self.object = self.get_object()
        
        self.object.delete()
        messages.add_message(request, messages.INFO, "Case deleted with success!")
        return redirect('cases_list') 
Example #27
Source File: views.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def populate(request):
#    pathway = Pathway(keggid='1234', name='Raony', genes='ABGS,SAKHA,AKJSKJ')
#    pathway.save()

    Pathway.objects.all().delete()

    pathways = kegg_rest_request('list/pathway/hsa')
    pathways = parse_pathways(pathways)
    insert_list = []
    total = len(pathways)
    
    for keggid in pathways:
        print(total)
        total = total-1
        
#        print keggid, pathways[keggid]
        pathway_data = kegg_rest_request('get/hsa%s' % (keggid))
        genes = parse_genes(pathway_data)
        print('genes')
#        print genes
        gene_list = []
        for gene in genes:
            gene_list.append(gene['symbol'])
#        print gene_list
        gene_list = ",".join(gene_list)
#        print keggid, pathways[keggid], gene_list
#        pathway_name = pathway_data.split('\n')[1].replace('NAME', '')
    
        pathway = Pathway(kegg=keggid, name=pathways[keggid], genes=gene_list)
        pathway.save()

    message = 'finish filling pathway from kegg'
    messages.add_message(request, messages.INFO, message)
    return redirect('/databases/')


# Create your views here. 
Example #28
Source File: views.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def populate(request):
#    pathway = Pathway(keggid='1234', name='Raony', genes='ABGS,SAKHA,AKJSKJ')
#    pathway.save()

    Pathway.objects.all().delete()

    pathways = kegg_rest_request('list/pathway/hsa')
    pathways = parse_pathways(pathways)
    insert_list = []
    total = len(pathways)
    
    for keggid in pathways:
        print(total)
        total = total-1
        
#        print keggid, pathways[keggid]
        pathway_data = kegg_rest_request('get/hsa%s' % (keggid))
        genes = parse_genes(pathway_data)
        print('genes')
#        print genes
        gene_list = []
        for gene in genes:
            gene_list.append(gene['symbol'])
#        print gene_list
        gene_list = ",".join(gene_list)
#        print keggid, pathways[keggid], gene_list
#        pathway_name = pathway_data.split('\n')[1].replace('NAME', '')
    
        pathway = Pathway(kegg=keggid, name=pathways[keggid], genes=gene_list)
        pathway.save()

    message = 'finish filling pathway from kegg'
    messages.add_message(request, messages.INFO, message)
    return redirect('/databases/')


# Create your views here. 
Example #29
Source File: views.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete(self, request, *args, **kwargs):
        """
        This does not actually delete the file, only the database record.  But
        that is easy to implement.
        """
        self.object = self.get_object()
        
        #username = self.object.user.username
        
        self.object.delete()
        messages.add_message(request, messages.INFO, "Group deleted with success!")
        return redirect('individuals_list') 
Example #30
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def alter_org_status(request, pk):
    try:
        obj = Organization.objects.get(pk=int(pk))
            # alter status method on custom user
        if obj.is_active:
            obj.is_active = False
            messages.info(request, 'Organization {0} Deactivated.'.format(obj.name))
        else:
            obj.is_active = True
            messages.info(request, 'Organization {0} Activated.'.format(obj.name))
        obj.save()
    except:
        messages.info(request, 'Organization {0} not found.'.format(obj.name))
    return HttpResponseRedirect(reverse('fieldsight:organizations-list'))

#
# @login_required
# @group_required('admin')
# def add_org_admin_old(request, pk):
#     obj = get_object_or_404(
#         Organization, id=pk)
#     if request.method == 'POST':
#         form = SetOrgAdminForm(request.POST)
#         user = int(form.data.get('user'))
#         group = Group.objects.get(name__exact="Organization Admin")
#         role = UserRole(user_id=user, group=group, organization=obj)
#         role.save()
#         messages.add_message(request, messages.INFO, 'Organization Admin Added')
#         return HttpResponseRedirect(reverse('fieldsight:organizations-list'))
#     else:
#         form = SetOrgAdminForm(instance=obj)
#     return render(request, "fieldsight/add_admin.html", {'obj':obj,'form':form})