Python django.views.generic.TemplateView() Examples

The following are 16 code examples of django.views.generic.TemplateView(). 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.views.generic , or try the search function .
Example #1
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_queryset(self, **kwargs):
        queryset = Site.objects.filter(project_id=self.kwargs.get('pk'), is_survey=False, is_active=True)
        
        if self.kwargs.get('region_id') == "0":
            object_list = queryset.filter(region=None)
        else:    
            object_list = queryset.filter(region_id=self.kwargs.get('region_id'))
        return object_list

# class RegionalSitelist(ProjectRoleMixin, TemplateView):
#     def get(self, request, *args, **kwargs):
#         queryset = Site.objects.filter(project_id=self.kwargs.get('pk'), is_survey=False, is_active=True)
#         if self.kwargs.get('region_id') == "0":
#             object_list = queryset.filter(region=None)
#         else:    
#             object_list = queryset.filter(region_id=self.kwargs.get('region_id'))
#         if self.kwargs.get('region_id') == "0":
#             return render(request, 'fieldsight/site_list.html',{'object_list':object_list, 'project_id':self.kwargs.get('pk'),'type':"Unregioned", 'pk': self.kwargs.get('pk'),'region_id':self.kwargs.get('region_id'),})
        
#         obj = get_object_or_404(Region, id=self.kwargs.get('region_id'))
#         return render(request, 'fieldsight/site_list.html',{'object_list':object_list, 'obj':obj, 'type':"region", 'pk': self.kwargs.get('pk'), 'region_id':self.kwargs.get('region_id'),})

# class RegionalSitelist(ProjectRoleMixin, ListView):
#     paginate_by = 10
#     def get(self, request, *args, **kwargs):
#         if self.kwargs.get('region_pk') == "0":
#             sites = Site.objects.filter(region=None)
#             return render(request, 'fieldsight/site_list.html' ,{'all_sites':sites, 'project_id':self.kwargs.get('pk'),'type':"Unregioned",'pk':self.kwargs.get('region_pk'),})

#         obj = get_object_or_404(Region, id=self.kwargs.get('region_pk'))
#         sites = Site.objects.filter(region_id=self.kwargs.get('region_pk'))
#         return render(request, 'fieldsight/site_list.html',{'all_sites':sites, 'obj':obj, 'type':"region",'pk':self.kwargs.get('region_pk'),}) 
Example #2
Source File: abstract.py    From django-flexible-subscriptions with GNU General Public License v3.0 5 votes vote down vote up
def get_context_data(self, **kwargs):
        """Overriding get_context_data to add additional context."""
        context = super(TemplateView, self).get_context_data(**kwargs)

        # Provides the base template to extend from
        context['template_extends'] = self.template_extends

        return context 
Example #3
Source File: views.py    From codesy with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_context_data(self, **kwargs):
        ctx = super(TemplateView, self).get_context_data(**kwargs)
        ctx['return_url'] = self.request.GET.get('return_url', '')
        return ctx 
Example #4
Source File: views.py    From mrs with GNU Affero General Public License v3.0 5 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        self.object = self.get_object()

        if not self.object:
            self.template_name = 'mrsrequest/notfound.html'
            return generic.TemplateView.get(self, request, *args, **kwargs)

        return super().dispatch(request, *args, **kwargs) 
Example #5
Source File: views.py    From mrs with GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        if self.object.status != self.object.STATUS_NEW:
            return http.HttpResponseBadRequest()

        self.object.status = self.object.STATUS_CANCELED
        self.object.status_datetime = datetime.now()
        self.object.save()

        self.object.logentries.create(
            action=MRSRequest.STATUS_CANCELED,
            comment='Annulation',
        )

        body = template.loader.get_template(
            'mrsrequest/cancelation_email.txt'
        ).render(dict(object=self.object, base_url=settings.BASE_URL)).strip()

        Caller(
            callback='djcall.django.email_send',
            kwargs=dict(
                subject=f'MRS: Annulation demande {self.object.display_id}',
                body=body.strip(),
                to=[self.object.insured.email],
                reply_to=[self.object.caisse.liquidation_email],
            )
        ).spool('mail')

        return generic.TemplateView.get(self, request, *args, **kwargs) 
Example #6
Source File: views.py    From Django-Blog-Python-Learning with GNU General Public License v2.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        context = self.get_context_data()
        if context['form'].is_valid():
            cd = context['form'].cleaned_data
            subject = cd['subject']
            from_email = cd['email']
            message = cd['message']

            try:
                send_mail(
                    subject + " from {}".format(from_email),
                    message,
                    from_email,
                    [settings.EMAIL_HOST_USER]
                )
            except BadHeaderError:
                return HttpResponse('Invalid header found.')

            ctx = {
                'success': """Thankyou, We appreciate that you've
                taken the time to write us.
                We'll get back to you very soon.
                Please come back and see us often."""
            }
            return render(request, self.template_name, ctx)
        return super(generic.TemplateView, self).render_to_response(context) 
Example #7
Source File: views.py    From protwis with Apache License 2.0 5 votes vote down vote up
def get_context_data(self, **kwargs):
        """get context from parent class (really only relevant for child classes of this class, as TemplateView does
        not have any context variables)"""
        context = super().get_context_data(**kwargs)

        # get selection from session and add to context
        # get simple selection from session
        simple_selection = self.request.session.get('selection', False)

        # create full selection and import simple selection (if it exists)
        selection = Selection()
        if simple_selection:
            selection.importer(simple_selection)

        # context['selection'] = selection
        context['selection'] = {}
        context['selection']['site_residue_groups'] = selection.site_residue_groups
        context['selection']['active_site_residue_group'] = selection.active_site_residue_group
        for selection_box, include in self.selection_boxes.items():
            if include:
                context['selection'][selection_box] = selection.dict(selection_box)['selection'][selection_box]

        # get attributes of this class and add them to the context
        attributes = inspect.getmembers(self, lambda a:not(inspect.isroutine(a)))
        for a in attributes:
            if not(a[0].startswith('__') and a[0].endswith('__')):
                context[a[0]] = a[1]
        return context 
Example #8
Source File: views.py    From protwis with Apache License 2.0 5 votes vote down vote up
def get_context_data(self, **kwargs):
        """get context from parent class (really only relevant for child classes of this class, as TemplateView does
        not have any context variables)"""
        context = super().get_context_data(**kwargs)

        # get selection from session and add to context
        # get simple selection from session
        simple_selection = self.request.session.get('selection', False)

        # create full selection and import simple selection (if it exists)
        selection = Selection()

        # on the first page of a workflow, clear the selection (or dont' import from the session)
        if self.step is not 1:
            if simple_selection:
                selection.importer(simple_selection)

        context['selection'] = {}
        context['selection']['tree_settings'] = selection.tree_settings

        for selection_box, include in self.selection_boxes.items():
            if include:
                context['selection'][selection_box] = selection.dict(selection_box)['selection'][selection_box]

        # get attributes of this class and add them to the context
        attributes = inspect.getmembers(self, lambda a:not(inspect.isroutine(a)))
        for a in attributes:
            if not(a[0].startswith('__') and a[0].endswith('__')):
                context[a[0]] = a[1]
        return context 
Example #9
Source File: views.py    From mapstory with GNU General Public License v3.0 5 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super(TemplateView, self).get_context_data(**kwargs)
        context['regions'] = Region.objects.filter(level=1)
        return context 
Example #10
Source File: views.py    From avos with Apache License 2.0 5 votes vote down vote up
def render_to_response(self, *args, **kwargs):
        response = super(TabView, self).render_to_response(*args, **kwargs)
        # Because Django's TemplateView uses the TemplateResponse class
        # to provide deferred rendering (which is usually helpful), if
        # a tab group raises an Http302 redirect (from exceptions.handle for
        # example) the exception is actually raised *after* the final pass
        # of the exception-handling middleware.
        response.render()
        return response 
Example #11
Source File: __init__.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def render_to_response(self, context, **response_kwargs):
        response_kwargs["content_type"] = "text/plain"
        return super(TemplateView, self).render_to_response(
            context, **response_kwargs
        ) 
Example #12
Source File: views.py    From django_twitter with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_context_data(self, hashtag):
        context = super(TemplateView, self).get_context_data()

        hashtag = hashtag.lower()
        feed = feed_manager.get_feed('user', f'hash_{hashtag}')
        activities = feed.get(limit=25)['results']

        context['hashtag'] = hashtag
        context['activities'] = enricher.enrich_activities(activities)

        return context 
Example #13
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def post(self, request, pk, *args, **kwargs):
        data = json.loads(self.request.body)
        projects = data.get('projects')
        users = data.get('users')
        group = Group.objects.get(name=data.get('group'))
        group_id = Group.objects.get(name="Project Manager").id
        user = request.user
        org = get_object_or_404(Organization, pk=pk)
        task_obj = CeleryTaskProgress.objects.create(user=user, content_object = org, task_type=1)
        if task_obj:
            task = multiuserassignproject.delay(task_obj.pk, user, pk, projects, users, group_id)
            task_obj.task_id=task.id
            task_obj.save()
            return HttpResponse("Sucess")
        else:
            return HttpResponse("Failed")


#May need it
# class MultiUserAssignProjectView(OrganizationRoleMixin, TemplateView):
#     def get(self, request, pk):
#         org_obj = Organization.objects.get(pk=pk)
#         return render(request, 'fieldsight/multi_user_assign.html',{'type': "project", 'pk':pk})

#     def post(self, request, *args, **kwargs):
#         data = json.loads(self.request.body)
#         projects = data.get('projects')
#         users = data.get('users')
     

#         group = Group.objects.get(name="Project Manager")
#         for project_id in projects:
#             project = Project.objects.get(pk=project_id)
#             for user in users:
#                 role, created = UserRole.objects.get_or_create(user_id=user, project_id=project_id,
#                                                                organization__id=project.organization.id,
#                                                                project__id=project_id,
#                                                                group=group, ended_at=None)
#                 if created:
#                     description = "{0} was assigned  as Project Manager in {1}".format(
#                         role.user.get_full_name(), role.project)
#                     noti = role.logs.create(source=role.user, type=6, title=description, description=description,
#                      content_object=role.project, extra_object=self.request.user)
#                     result = {}
#                     result['description'] = description
#                     result['url'] = noti.get_absolute_url()
#                     ChannelGroup("notify-{}".format(role.organization.id)).send({"text": json.dumps(result)})
#                     ChannelGroup("project-{}".format(role.project.id)).send({"text": json.dumps(result)})
#                     ChannelGroup("notify-0").send({"text": json.dumps(result)})
#         return HttpResponse("Sucess") 
Example #14
Source File: views.py    From website with GNU General Public License v3.0 4 votes vote down vote up
def get_context_data(self, **kwargs):
        # Make sure both the Community, Project, and mentor are approved
        # Note that accessing URL parameters like project_slug off kwargs only
        # works because this is a TemplateView. For the various kinds of
        # DetailViews, you have to use self.kwargs instead.
        project = get_object_or_404(Project,
                slug=kwargs['project_slug'],
                approval_status=ApprovalStatus.APPROVED,
                project_round__community__slug=kwargs['community_slug'],
                project_round__participating_round__slug=kwargs['round_slug'],
                project_round__approval_status=ApprovalStatus.APPROVED)

        current_round = project.round()

        # Note that there's no reason to ever keep someone who was a
        # coordinator or mentor in a past round from looking at who applied in
        # that round.

        if not self.request.user.is_staff and not project.project_round.community.is_coordinator(self.request.user) and not project.round().is_mentor(self.request.user):
            raise PermissionDenied("You are not an approved mentor for this project.")

        contributions = project.contribution_set.filter(
                applicant__approval_status=ApprovalStatus.APPROVED).order_by(
                "applicant__applicant__public_name", "date_started")
        internship_total_days = current_round.internends - current_round.internstarts
        try:
            mentor_approval = project.mentorapproval_set.approved().get(
                mentor__account=self.request.user,
            )
        except MentorApproval.DoesNotExist:
            mentor_approval = None

        context = super(ProjectApplicants, self).get_context_data(**kwargs)
        context.update({
            'current_round': current_round,
            'community': project.project_round.community,
            'project': project,
            'contributions': contributions,
            'internship_total_days': internship_total_days,
            'approved_mentor': project.is_submitter(self.request.user),
            'is_staff': self.request.user.is_staff,
            'mentor_approval': mentor_approval,
            })
        return context 
Example #15
Source File: views.py    From protwis with Apache License 2.0 4 votes vote down vote up
def get_context_data(self, **kwargs):
        """get context from parent class (really only relevant for children of this class, as TemplateView does
        not have any context variables)"""
        context = super().get_context_data(**kwargs)

        # get selection from session and add to context
        # get simple selection from session
        simple_selection = self.request.session.get('selection', False)

        # create full selection and import simple selection (if it exists)
        selection = Selection()

        # on the first page of a workflow, clear the selection (or dont' import from the session)
        if self.step is not 1:
            if simple_selection:
                selection.importer(simple_selection)

        # default species selection
        if self.default_species:
            sp = Species.objects.get(common_name=self.default_species)
            o = SelectionItem('species', sp)
            selection.species = [o]

        # update session
        simple_selection = selection.exporter()
        self.request.session['selection'] = simple_selection

        context['selection'] = {}
        for selection_box, include in self.selection_boxes.items():
            if include:
                context['selection'][selection_box] = selection.dict(selection_box)['selection'][selection_box]

        if self.filters:
            context['selection']['species'] = selection.species
            context['selection']['annotation'] = selection.annotation
            context['selection']['g_proteins'] = selection.g_proteins
            context['selection']['pref_g_proteins'] = selection.pref_g_proteins

        # get attributes of this class and add them to the context
        attributes = inspect.getmembers(self, lambda a:not(inspect.isroutine(a)))
        for a in attributes:
            if not(a[0].startswith('__') and a[0].endswith('__')):
                context[a[0]] = a[1]
        return context 
Example #16
Source File: views.py    From mrs with GNU Affero General Public License v3.0 3 votes vote down vote up
def post_rating(self, request, *args, **kwargs):
        self.mrsrequest_uuid = self.request.POST.get(
            'rating-mrsrequest_uuid', None)
        if not self.has_perm(exists=True):
            return http.HttpResponseBadRequest()

        self.rating_form = RatingForm(request.POST, prefix='rating')
        self.rating_form.instance.mrsrequest = MRSRequest.objects.get(
            pk=self.mrsrequest_uuid
        )

        if self.rating_form.is_valid():
            with transaction.atomic():
                self.success_rating = self.rating_form.save()

        return generic.TemplateView.get(self, request, *args, **kwargs)