Python django.contrib.messages.info() Examples

The following are 30 code examples for showing how to use django.contrib.messages.info(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.contrib.messages , or try the search function .

Example 1
Project: Servo   Author: fpsw   File: order.py    License: 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
Project: coursys   Author: sfu-fas   File: views.py    License: 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 3
Project: django-idcops   Author: Wenvki   File: mixins.py    License: 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 4
Project: lmgtdfy   Author: opendata   File: views.py    License: 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 5
Project: lmgtdfy   Author: opendata   File: views.py    License: 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 6
Project: kobo-predict   Author: awemulya   File: views.py    License: 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 7
Project: kobo-predict   Author: awemulya   File: views.py    License: 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 8
Project: kobo-predict   Author: awemulya   File: views.py    License: 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 9
Project: kobo-predict   Author: awemulya   File: views.py    License: 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
Project: peering-manager   Author: respawner   File: views.py    License: 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 11
Project: DCRM   Author: 82Flex   File: release.py    License: 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 12
Project: BikeMaps   Author: SPARLab   File: views.py    License: 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 13
Project: fermentrack   Author: thorrak   File: profile_views.py    License: 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 14
Project: fermentrack   Author: thorrak   File: profile_views.py    License: 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 15
Project: tom_base   Author: TOMToolkit   File: views.py    License: 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 16
Project: tom_base   Author: TOMToolkit   File: views.py    License: 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 17
Project: pasportaservo   Author: tejoesperanto   File: views.py    License: 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 18
Project: civet   Author: idaholab   File: oauth_api.py    License: 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 19
Project: civet   Author: idaholab   File: oauth_api.py    License: 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 20
Project: civet   Author: idaholab   File: oauth_api.py    License: 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 21
Project: civet   Author: idaholab   File: views.py    License: 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 22
Project: Servo   Author: fpsw   File: account.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def logout(request):
    if request.method == 'POST':
        auth.logout(request)
        messages.info(request, _("You have logged out"))

        return redirect(login)

    return render(request, "accounts/logout.html") 
Example 23
Project: Servo   Author: fpsw   File: order.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def remove_device(request, order_id, device_id):
    action = request.path
    order = Order.objects.get(pk=order_id)
    device = Device.objects.get(pk=device_id)

    if request.method == "POST":
        msg = order.remove_device(device, request.user)
        messages.info(request, msg)
        return redirect(order)

    return render(request, "orders/remove_device.html", locals()) 
Example 24
Project: Servo   Author: fpsw   File: order.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def reserve_products(request, pk):
    order = get_object_or_404(Order, pk=pk)

    if request.method == 'POST':
        for p in order.products.all():
            p.reserve_product()

        msg = _(u"Products of order %s reserved") % order.code
        order.notify("products_reserved", msg, request.user)
        messages.info(request, msg)

        return redirect(order)

    return render(request, "orders/reserve_products.html", locals()) 
Example 25
Project: crowdata   Author: crowdata   File: admin.py    License: MIT License 5 votes vote down vote up
def add_documents_view(self, request, document_set_id):
        """ add a bunch of documents to
         a DocumentSet by uploading a CSV """
        document_set = get_object_or_404(self.model, pk=document_set_id)
        if request.FILES.get('csv_file'):
            # got a CSV, process, check and create
            csvreader = csv.reader(request.FILES.get('csv_file'))

            header_row = csvreader.next()
            if [h.strip() for h in header_row] != ['document_title', 'document_url']:
                messages.error(request,
                               _('Header cells must be document_title and document_url'))


            count = 0
            try:
                with transaction.commit_on_success():
                    for row in csvreader:
                        document_set.documents.create(name=row[0].strip(),
                                                      url=row[1].strip())
                        count += 1
            except:
                messages.error(request,
                               _('Could not create documents'))

                return redirect(reverse('admin:document_set_add_documents',
                                        args=(document_set_id,)))

            messages.info(request,
                          _('Successfully created %(count)d documents') % { 'count': count })

            return redirect(reverse('admin:crowdataapp_documentset_changelist'))

        else:
            return render_to_response('admin/document_set_add_documents.html',
                                      {
                                          'document_set': document_set,
                                          'current_app': self.admin_site.name,
                                      },
                                      RequestContext(request)) 
Example 26
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def page_version(request, course_slug, page_label, version_id):
    offering = get_object_or_404(CourseOffering, slug=course_slug)
    page = get_object_or_404(Page, offering=offering, label=page_label)
    member = _check_allowed(request, offering, page.can_write, page.editdate())
    # check that we have an allowed member of the course (and can continue)
    if not member:
        return _forbidden_response(request, page.get_can_write_display())
    
    version = get_object_or_404(PageVersion, page=page, id=version_id)
    
    messages.info(request, "This is an old version of this page.")
    context = {'offering': offering, 'page': page, 'version': version,
               'is_old': True}
    return render(request, 'pages/view_page.html', context) 
Example 27
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def student_search(request, course_slug):
    course = get_object_or_404(CourseOffering, slug=course_slug)
    if request.method == 'POST':
        # find the student if we can and redirect to info page
        form = StudentSearchForm(request.POST)
        if not form.is_valid():
            messages.add_message(request, messages.ERROR, 'Invalid search')
            context = {'course': course, 'form': form}
            return render(request, 'grades/student_search.html', context)

        search = form.cleaned_data['search']
        try:
            int(search)
            students = Member.objects.filter(offering=course, role="STUD").filter(Q(person__userid=search) | Q(person__emplid=search))
        except ValueError:
            students = Member.objects.filter(offering=course, role="STUD").filter(person__userid=search)
        
        if len(students)!=1:
            if len(students)==0:
                messages.add_message(request, messages.ERROR, 'No student found')
            else:
                messages.add_message(request, messages.ERROR, 'Multiple students found')
            context = {'course': course, 'form': form}
            return render(request, 'grades/student_search.html', context)

        student = students[0]
        return HttpResponseRedirect(reverse('offering:student_info',
                                                kwargs={'course_slug': course_slug, 'userid': student.person.userid}))


    form = StudentSearchForm()
    context = {'course': course, 'form': form}
    return render(request, 'grades/student_search.html', context) 
Example 28
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def faculty_member_info(request, userid):
    person, _ = _get_faculty_or_404(request.units, userid)
    info = FacultyMemberInfo.objects.filter(person=person).first()

    can_modify = True
    can_view_emergency = True

    context = {
        'person': person,
        'info': info,
        'can_modify': can_modify,
        'can_view_emergency': can_view_emergency,
    }
    return render(request, 'faculty/faculty_member_info.html', context) 
Example 29
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def import_grants(request):
    editor = get_object_or_404(Person, userid=request.user.username)
    units = Unit.sub_units(request.units)
    form = GrantImportForm(request.POST, request.FILES)
    if form.is_valid():
        csvfile = form.cleaned_data["file"]
        created, failed = TempGrant.objects.create_from_csv(csvfile, editor, units)
        if failed:
            messages.error(request, "Created %d grants, %d failed" % (len(created), len(failed)))
        else:
            messages.info(request, "Created %d grants" % (len(created)))
    return HttpResponseRedirect(reverse("faculty:grant_index")) 
Example 30
Project: rainmap-lite   Author: cldrn   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def clear_logs(request):
    """Clear admin activity logs if user has permissions"""

    if not request.user.is_authenticated(): # should be applied to anything under /console
        return redirect('login')

    if request.user.has_perm('admin.delete_logentry'):
        LogEntry.objects.all().filter(user__pk=request.user.id).delete()
        messages.info(request, 'Successfully cleared admin activity logs.', fail_silently=True)
    else:
        messages.warning(request, 'Unable to clear the admin activity logs.', fail_silently=True)

    return redirect('admin:index')