Esempio n. 1
0
def oneoff(request, id):
    """ This form is for adding oneoff fees to an event """
    context = {}
    context['msg'] = "One-Off Charges"

    event = get_object_or_404(BaseEvent, pk=id)
    context['event'] = event

    if not (request.user.has_perm('events.adjust_event_charges') or
            request.user.has_perm('events.adjust_event_charges', event)):
        raise PermissionDenied
    if event.closed:
        messages.add_message(request, messages.ERROR, 'Event is closed.')
        return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))

    mk_oneoff_formset = inlineformset_factory(BaseEvent, EventArbitrary, extra=3, exclude=[])

    if request.method == 'POST':
        set_revision_comment("Edited billing charges", None)
        formset = mk_oneoff_formset(request.POST, request.FILES, instance=event)
        if formset.is_valid():
            formset.save()
            event.save() # for revision to be created
            return HttpResponseRedirect(reverse('events:detail', args=(event.id,)) + "#billing")
        else:
            context['formset'] = formset

    else:
        formset = mk_oneoff_formset(instance=event)

        context['formset'] = formset

    return render(request, 'formset_crispy_arbitrary.html', context)
Esempio n. 2
0
def assignattach_external(request, id):
    context = {}

    event = get_object_or_404(Event, pk=id)
    if event.closed:
        messages.add_message(request, messages.ERROR, 'Event is closed.')
        return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))

    context['event'] = event

    mk_att_formset = inlineformset_factory(Event, EventAttachment, extra=1, exclude=[])
    # mk_att_formset.queryset = mk_att_formset.queryset.filter(externally_uploaded=True)
    mk_att_formset.form = curry_class(AttachmentForm, event=event, externally_uploaded=True)

    if request.method == 'POST':
        set_revision_comment("Edited attachments", None)
        formset = mk_att_formset(request.POST, request.FILES, instance=event,
                                 queryset=EventAttachment.objects.filter(externally_uploaded=True))
        if formset.is_valid():
            f = formset.save(commit=False)
            for i in f:
                i.externally_uploaded = True
                i.save()
            event.save() # for revision to be created
            return HttpResponseRedirect(reverse('my:workorders', ))
        else:
            context['formset'] = formset

    else:
        formset = mk_att_formset(instance=event, queryset=EventAttachment.objects.filter(externally_uploaded=True))

        context['formset'] = formset

    return render(request, 'formset_crispy_attachments.html', context)
Esempio n. 3
0
def org_mkxfer(request, id):
    context = {}
    org = get_object_or_404(Organization, pk=id)
    if not request.user.has_perm('events.transfer_org_ownership', org):
        raise PermissionDenied
    context['msg'] = 'Orgs: <a href="%s">%s</a> &middot; Transfer Ownership' % (
        reverse("orgs:detail", args=(org.id,)), org.name)
    user = request.user
    now = timezone.now()
    wfn = now + datetime.timedelta(days=7)

    if request.method == "POST":
        form = OrgXFerForm(org, user, request.POST)
        if form.is_valid():
            f = form.save(commit=False)
            f.expiry = wfn
            f.save()
            if settings.SEND_EMAIL_ORG_TRANSFER:
                email = generate_transfer_email(f)
                email.send()
            if email:
                messages.add_message(request, messages.SUCCESS, 'Created transfer request. To complete \
                the transfer, you must use the link that was just emailed to ' + ', '.join(email.to))
            else:
                messages.add_message(request, messages.SUCCESS, 'Created transfer request. To complete \
                the transfer, you must use the link that was just emailed.')
            return HttpResponseRedirect(reverse("orgs:detail", args=(org.id,)))

    else:
        form = OrgXFerForm(org, user)
        context['formset'] = form

    return render(request, 'mycrispy.html', context)
Esempio n. 4
0
    def related_link(self, instance):
        links = []
        for rel, view_perm, add_perm in self.get_related_list():
            opts = rel.related_model._meta

            label = opts.app_label
            model_name = opts.model_name

            field = rel.field
            rel_name = rel.get_related_field().name

            verbose_name = force_text(opts.verbose_name)
            lookup_name = '%s__%s__exact' % (field.name, rel_name)

            link = ''.join(('<li class="with_menu_btn">',

                            '<a href="%s?%s=%s" title="%s"><i class="icon fa fa-th-list"></i> %s</a>' %
                            (
                                reverse('%s:%s_%s_changelist' % (
                                    self.admin_site.app_name, label, model_name)),
                                RELATE_PREFIX + lookup_name, str(instance.pk), verbose_name, verbose_name) if view_perm else
                            '<a><span class="text-muted"><i class="icon fa fa-blank"></i> %s</span></a>' % verbose_name,

                            '<a class="add_link dropdown-menu-btn" href="%s?%s=%s"><i class="icon fa fa-plus pull-right"></i></a>' %
                            (
                                reverse('%s:%s_%s_add' % (
                                    self.admin_site.app_name, label, model_name)),
                                RELATE_PREFIX + lookup_name, str(
                                    instance.pk)) if add_perm else "",

                            '</li>'))
            links.append(link)
        ul_html = '<ul class="dropdown-menu" role="menu">%s</ul>' % ''.join(
            links)
        return '<div class="dropdown related_menu pull-right"><a title="%s" class="relate_menu dropdown-toggle" data-toggle="dropdown"><i class="icon fa fa-list"></i></a>%s</div>' % (_('Related Objects'), ul_html)
Esempio n. 5
0
    def test_replace_title_in_text_with_links(self):
        title1 = u"1) Самая лучшая экскурсия от 240 руб."
        ex1 = Excursion.objects.create(
            title=title1
        )
        url1 = reverse('excursions:item', args=[ex1.pk, ex1.title])

        title2 = u"Самая (лучшая) экскурсия.? от"
        ex2 = Excursion.objects.create(
            title=title2
        )
        url2 = reverse('excursions:item', args=[ex2.pk, ex2.title])

        comment = u"Проснулся я ночью часа в два {{{title1}}} \n" \
                  u"провелась у меня {{{title2}}}, {{{title2}}}{{{title1}}}".format(title1=title1,
                                                                                    title2=title2)
        expected_comment = u"Проснулся я ночью часа в два <a href=\"{url1}\">{title1}</a> \n" \
                           u"провелась у меня <a href=\"{url2}\">{title2}</a>, " \
                           u"<a href=\"{url2}\">{title2}</a><a href=\"{url1}\">{title1}</a>".format(
            url1=url1, url2=url2, title1=title1, title2=title2)
        result = ExcursionCalendar.replace_with_links(comment)

        self.assertEqual(expected_comment, result)

        ex = ExcursionCalendar.objects.create(
            comment=comment
        )
        self.assertEqual(ex.comment_rendered, ExcursionCalendar.replace_with_links(ex.comment))
Esempio n. 6
0
def assigncc(request, id):
    context = {}

    event = get_object_or_404(BaseEvent, pk=id)

    if not (request.user.has_perm('events.edit_event_hours') or
            request.user.has_perm('events.edit_event_hours', event)):
        raise PermissionDenied
    if event.closed:
        messages.add_message(request, messages.ERROR, 'Event is closed.')
        return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
    context['event'] = event
    context['oldevent'] = isinstance(event, Event)

    cc_formset = inlineformset_factory(Event, EventCCInstance, extra=5, exclude=[])
    cc_formset.form = curry_class(CCIForm, event=event)

    if request.method == 'POST':
        formset = cc_formset(request.POST, instance=event)
        if formset.is_valid():
            formset.save()
            return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
        else:
            context['formset'] = formset

    else:
        formset = cc_formset(instance=event)

        context['formset'] = formset

    return render(request, 'formset_crispy_helpers.html', context)
Esempio n. 7
0
def assigncrew(request, id):
    context = {}
    context['msg'] = "Crew"

    event = get_object_or_404(Event, pk=id)
    if not (request.user.has_perm('events.edit_event_hours') or
            request.user.has_perm('events.edit_event_hours', event)):
        raise PermissionDenied
    if event.closed:
        messages.add_message(request, messages.ERROR, 'Event is closed.')
        return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
    context['event'] = event

    if request.method == 'POST':
        formset = CrewAssign(request.POST, instance=event)
        if formset.is_valid():
            formset.save()
            return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
        else:
            context['formset'] = formset

    else:
        formset = CrewAssign(instance=event)

        context['formset'] = formset

    return render(request, 'form_crew_add.html', context)
    def get_section(self, app_config=None):
        """Returns a dictionary for a single section.

        Format is {verbose_name: url_name}

        To be included must be a registered namespace. To main apps
        urls.py add paths. For example for `ambition_export`:

            urlpatterns = [
            ...
            path('admin/', ambition_export_admin.urls),
            path('ambition_export/', include('ambition_export.urls')),
            ...
            ]

        """
        section = {}
        try:
            url_namespace = app_config.url_namespace
        except AttributeError:
            url_namespace = app_config.name
        try:
            url = app_config.home_url_name
        except AttributeError:
            url = f'{url_namespace}:home_url'
        try:
            reverse(url)
        except NoReverseMatch:
            # probably is not a registered namespace
            pass
        else:
            section = {app_config.verbose_name: url}
        return section
Esempio n. 9
0
    def get_success_url(self):
        text_message = _(
            'Thank you for your help. We will check your problem as soon as we can')
        messages.add_message(self.request, messages.SUCCESS, text_message)
        try:
            lab_pk = int(self.request.GET.get('lab_pk', 0))
        except:
            lab_pk = None
        dev = reverse('index')
        if self.request.user.is_authenticated():
            self.object.user = self.request.user
        if lab_pk:
            self.object.laboratory_id = lab_pk
            dev = reverse('laboratory:labindex', kwargs={'lab_pk': lab_pk})
        if self.request.user.is_authenticated() or lab_pk:
            self.object.save()

        send_email_from_template("New feedback",
                                 settings.DEFAULT_FROM_EMAIL,
                                 context={
                                     'feedback': self.object
                                 },
                                 enqueued=True,
                                 user=None,
                                 upfile=self.object.related_file)

        return dev
Esempio n. 10
0
def reviewremind(request, id, uid):
    event = get_object_or_404(Event, pk=id)
    if not (request.user.has_perm('events.review_event') or
            request.user.has_perm('events.review_event', event)):
        raise PermissionDenied
    if event.closed:
        messages.add_message(request, messages.ERROR, 'Event is closed.')
        return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
    if event.reviewed or not event.approved:
        messages.add_message(request, messages.ERROR, 'Can only send reminders for an event that is approved and not reviewed.')
        return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))

    cci = event.ccinstances.filter(crew_chief_id=uid)
    if cci:
        # only do heavy lifting if we need to

        pdf_handle = generate_pdfs_standalone([event.id])
        filename = "%s.workorder.pdf" % slugify(event.event_name)
        attachments = [{"file_handle": pdf_handle, "name": filename}]

        cci = cci[0]
        reminder = ReportReminder.objects.create(event=cci.event, crew_chief=cci.crew_chief)
        email = ReportReminderEmailGenerator(reminder=reminder, attachments=attachments)
        email.send()
        messages.add_message(request, messages.INFO, 'Reminder Sent')
        return HttpResponseRedirect(reverse("events:review", args=(event.id,)))
    else:
        return HttpResponse("Bad Call")
Esempio n. 11
0
    def context(self, context):
        btns = []
        for b in self.q_btns:
            btn = {}
            if 'model' in b:
                model = self.get_model(b['model'])
                if not self.user.has_perm("%s.view_%s" % (model._meta.app_label, model._meta.model_name)):
                    continue
                btn['url'] = reverse("%s:%s_%s_%s" % (self.admin_site.app_name, model._meta.app_label,
                                                      model._meta.model_name, b.get('view', 'changelist')))
                btn['title'] = model._meta.verbose_name
                btn['icon'] = self.dashboard.get_model_icon(model)
            else:
                try:
                    btn['url'] = reverse(b['url'])
                except NoReverseMatch:
                    btn['url'] = b['url']

            if 'title' in b:
                btn['title'] = b['title']
            if 'icon' in b:
                btn['icon'] = b['icon']
            btns.append(btn)

        context.update({'btns': btns})
Esempio n. 12
0
def remindall(request, id):
    event = get_object_or_404(Event, pk=id)
    if not (request.user.has_perm('events.review_event') or
            request.user.has_perm('events.review_event', event)):
        raise PermissionDenied
    if event.closed:
        messages.add_message(request, messages.ERROR, 'Event is closed.')
        return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
    if event.reviewed or not event.approved:
        messages.add_message(request, messages.ERROR, 'Can only send reminders for an event that is approved and not reviewed.')
        return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))

    if event.num_crew_needing_reports == 0:
        messages.add_message(request, messages.INFO, 'All crew chiefs have already submitted reports.')
        return HttpResponseRedirect(reverse("events:review", args=(event.id,)))

    pdf_handle = generate_pdfs_standalone([event.id])
    filename = "%s.workorder.pdf" % slugify(event.event_name)
    attachments = [{"file_handle": pdf_handle, "name": filename}]

    for cci in event.crew_needing_reports:
        reminder = ReportReminder.objects.create(event=event, crew_chief=cci.crew_chief)
        email = ReportReminderEmailGenerator(reminder=reminder, attachments=attachments)
        email.send()

    messages.add_message(request, messages.INFO, 'Reminders sent to all crew chiefs needing reports for %s' % event.event_name)
    if 'next' in request.GET:
        return HttpResponseRedirect(request.GET['next'])
    else:
        return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
Esempio n. 13
0
def cancel(request, id):
    set_revision_comment("Cancelled", None)
    context = {}
    context['msg'] = "Event Cancelled"
    event = get_object_or_404(BaseEvent, pk=id)
    if not request.user.has_perm('events.cancel_event', event):
        raise PermissionDenied
    if event.closed:
        messages.add_message(request, messages.ERROR, 'Event is closed.')
        return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
    event.cancelled = True
    event.cancelled_by = request.user
    event.cancelled_on = timezone.now()
    event.save()

    if event.contact and event.contact.email:
        targets = [event.contact.email]
    else:
        targets = []

    email_body = 'The event "%s" has been cancelled by %s. If this is incorrect, please contact our vice president at [email protected].' % (event.event_name, str(request.user))
    if request.user.email:
        email_body = email_body[:-1]
        email_body += " or try them at %s." % request.user.email
    email = DLEG(subject="Event Cancelled", to_emails=targets, body=email_body, bcc=[settings.EMAIL_TARGET_VP])
    email.send()
    return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
Esempio n. 14
0
def hours_bulk_admin(request, id):
    context = {}

    context['msg'] = "Bulk Hours Entry"
    event = get_object_or_404(BaseEvent, pk=id)
    if not (request.user.has_perm('events.edit_event_hours') or
            request.user.has_perm('events.edit_event_hours', event) and event.reports_editable):
        raise PermissionDenied
    if event.closed:
        messages.add_message(request, messages.ERROR, 'Event is closed.')
        return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
    context['event'] = event
    context['oldevent'] = isinstance(event, Event)

    mk_hours_formset = inlineformset_factory(BaseEvent, Hours, extra=15, exclude=[])
    mk_hours_formset.form = curry_class(MKHoursForm, event=event)

    if request.method == 'POST':
        formset = mk_hours_formset(request.POST, instance=event)
        if formset.is_valid():
            formset.save()
            return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
    else:
        formset = mk_hours_formset(instance=event)

    context['formset'] = formset
    return render(request, 'formset_hours_bulk.html', context)
Esempio n. 15
0
def unreviewed(request, start=None, end=None):
    context = {}

    if not start and not end:
        today = datetime.date.today()
        start = today - datetime.timedelta(days=180)
        start = start.strftime('%Y-%m-%d')
        end = today + datetime.timedelta(days=180)
        end = end.strftime('%Y-%m-%d')

    now = datetime.datetime.now(pytz.utc)
    events = BaseEvent.objects.filter(approved=True, closed=False, cancelled=False) \
        .filter(reviewed=False) \
        .filter(datetime_end__lte=now) \
        .order_by('datetime_start') \
        .prefetch_related('crew_chief') \
        .distinct()
    if not request.user.has_perm('events.event_view_sensitive'):
        events = events.exclude(sensitive=True)
    if not request.user.has_perm('events.view_test_event'):
        events = events.exclude(test_event=True)
    events = events.select_related('location__building').prefetch_related('org') \
        .prefetch_related('ccinstances__crew_chief')
    if (not request.GET.get('projection') and request.COOKIES.get('projection')
        and request.COOKIES['projection'] != 'show'):
        return build_redirect(request, projection=request.COOKIES['projection'], **request.GET.dict())
    if request.GET.get('projection') == 'hide':
        events = events.exclude(
            (Q(Event___projection__isnull=False, Event___lighting__isnull=True, Event___sound__isnull=True) \
            | Q(serviceinstance__service__category__name='Projection')) \
            & ~Q(serviceinstance__service__category__name__in=Category.objects.exclude(name='Projection').values_list('name', flat=True)))
    elif request.GET.get('projection') == 'only':
        events = events.filter(Q(Event___projection__isnull=False) | Q(serviceinstance__service__category__name='Projection'))
    events, context = datefilter(events, context, start, end)

    page = request.GET.get('page')
    sort = request.GET.get('sort')
    events = paginate_helper(events, page, sort)

    context['h2'] = "Events Pending Billing Review"
    context['events'] = events
    context['baseurl'] = reverse("events:unreviewed")
    context['pdfurl_workorders'] = reverse('events:pdf-multi')
    context['pdfurl_bills'] = reverse('events:bill-pdf-multi')
    context['calurl'] = reverse('events:unreviewed-cal')
    context['takes_param_projection'] = True
    context['cols'] = ['event_name',
                       'org',
                       'location',
                       FakeExtendedField('datetime_start', verbose_name="Event Time"),
                       'crew_chief',
                       FakeField('num_crew_needing_reports', sortable=True, verbose_name="Missing Reports"),
                       FakeField('short_services', verbose_name="Services", sortable=False),
                       FakeField('tasks')]
    context['cols'] = map_fields(context['cols'])  # must use because there are strings
    response = render(request, 'events.html', context)
    if request.GET.get('projection') and request.GET['projection'] != request.COOKIES.get('projection'):
        response.set_cookie('projection', request.GET['projection'])
    return response
Esempio n. 16
0
def findchief(request, start=None, end=None):
    if not start and not end:
        today = datetime.date.today()
        start = today
        start = start.strftime('%Y-%m-%d')
        end = today + datetime.timedelta(days=30.5)
        end = end.strftime('%Y-%m-%d')
    context = {}

    events = BaseEvent.objects \
        .filter(approved=True).filter(closed=False).filter(cancelled=False) \
        .annotate(num_ccs=Count('ccinstances')) \
        .filter(Q(Event___ccs_needed__gt=F('num_ccs')) | Q(num_ccs__lt=Count('serviceinstance__service__category', distinct=True))).distinct()

    if not request.user.has_perm('events.event_view_sensitive'):
        events = events.exclude(sensitive=True)
    if not request.user.has_perm('events.view_test_event'):
        events = events.exclude(test_event=True)
    events = events.select_related('location__building').prefetch_related('org') \
        .prefetch_related('ccinstances__crew_chief')
    if (not request.GET.get('projection') and request.COOKIES.get('projection')
        and request.COOKIES['projection'] != 'show'):
        return build_redirect(request, projection=request.COOKIES['projection'], **request.GET.dict())
    if request.GET.get('projection') == 'hide':
        events = events.exclude(
            (Q(Event___projection__isnull=False, Event___lighting__isnull=True, Event___sound__isnull=True) \
            | Q(serviceinstance__service__category__name='Projection')) \
            & ~Q(serviceinstance__service__category__name__in=Category.objects.exclude(name='Projection').values_list('name', flat=True)))
    elif request.GET.get('projection') == 'only':
        events = events.filter(Q(Event___projection__isnull=False) | Q(serviceinstance__service__category__name='Projection'))

    events, context = datefilter(events, context, start, end)

    page = request.GET.get('page')
    sort = request.GET.get('sort') or 'datetime_start'
    events = paginate_helper(events, page, sort)

    context['h2'] = "Needs a Crew Chief"
    context['takes_param_projection'] = True
    context['events'] = events
    context['baseurl'] = reverse("events:findchief")
    context['pdfurl_workorders'] = reverse('events:pdf-multi')
    context['pdfurl_bills'] = reverse('events:bill-pdf-multi')
    context['calurl'] = reverse('events:findchief-cal')
    context['cols'] = ['event_name',
                       'org',
                       'location',
                       FakeExtendedField('datetime_start', verbose_name="Starting At"),
                       'submitted_on',
                       'num_ccs',
                       FakeField('eventcount', verbose_name="# Services"),
                       FakeField('short_services', verbose_name="Services", sortable=False)]
    context['cols'] = map_fields(context['cols'])  # must use because there are strings
    response = render(request, 'events.html', context)
    if request.GET.get('projection') and request.GET['projection'] != request.COOKIES.get('projection'):
        response.set_cookie('projection', request.GET['projection'])
    return response
Esempio n. 17
0
def rmcc(request, id, user):
    event = get_object_or_404(Event, pk=id)
    if not (request.user.has_perm('events.edit_event_hours') or
            request.user.has_perm('events.edit_event_hours', event)):
        raise PermissionDenied
    if event.closed:
        messages.add_message(request, messages.ERROR, 'Event is closed.')
        return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
    event.crew_chief.remove(user)
    return HttpResponseRedirect(reverse("events:chiefs", args=(event.id,)))
Esempio n. 18
0
def paid(request, start=None, end=None):
    context = {}

    if not start and not end:
        start, end = get_very_large_date_range()

    # events = Event.objects.filter(approved=True).filter(paid=True)
    events = BaseEvent.objects.filter(closed=False) \
        .filter(Q(billings__date_paid__isnull=False) | Q(multibillings__date_paid__isnull=False)) \
        .distinct()
    if not request.user.has_perm('events.event_view_sensitive'):
        events = events.exclude(sensitive=True)
    if not request.user.has_perm('events.view_test_event'):
        events = events.exclude(test_event=True)
    events = events.select_related('location__building').prefetch_related('org') \
        .prefetch_related('ccinstances__crew_chief').prefetch_related('billings')
    if (not request.GET.get('projection') and request.COOKIES.get('projection')
        and request.COOKIES['projection'] != 'show'):
        return build_redirect(request, projection=request.COOKIES['projection'], **request.GET.dict())
    if request.GET.get('projection') == 'hide':
        events = events.exclude(
            (Q(Event___projection__isnull=False, Event___lighting__isnull=True, Event___sound__isnull=True) \
            | Q(serviceinstance__service__category__name='Projection')) \
            & ~Q(serviceinstance__service__category__name__in=Category.objects.exclude(name='Projection').values_list('name', flat=True)))
    elif request.GET.get('projection') == 'only':
        events = events.filter(Q(Event___projection__isnull=False) | Q(serviceinstance__service__category__name='Projection'))
    events, context = datefilter(events, context, start, end)

    # if events:
    # events = events.latest('billings__date_paid') # limit further

    page = request.GET.get('page')
    sort = request.GET.get('sort')
    events = paginate_helper(events, page, sort)

    context['h2'] = "Paid Events"
    context['events'] = events
    context['baseurl'] = reverse("events:paid")
    context['pdfurl_workorders'] = reverse('events:pdf-multi')
    context['pdfurl_bills'] = reverse('events:bill-pdf-multi')
    context['calurl'] = reverse('events:paid-cal')
    context['takes_param_projection'] = True
    context['cols'] = ['event_name',
                       'org',
                       FakeExtendedField('datetime_start', verbose_name="Event Time"),
                       FakeField('last_billed', sortable=True),
                       FakeField('last_paid', verbose_name="Paid On", sortable=True),
                       FakeField('short_services', verbose_name="Services", sortable=False)]
    context['cols'] = map_fields(context['cols'])  # must use because there are strings
    response = render(request, 'events.html', context)
    if request.GET.get('projection') and request.GET['projection'] != request.COOKIES.get('projection'):
        response.set_cookie('projection', request.GET['projection'])
    return response
Esempio n. 19
0
 def test_upload_view_post_success_not_historical(self):
     upload_jobs_count = UploadJob.objects.count()
     self.client.login(username='******', password='******')
     response = self.client.post(
         reverse('simulation.upload'),
         data={'name': 'test', 'output_file': io.StringIO(''), 'historical': 'no', 'is_test': 'yes'}
     )
     self.assertEqual(response.status_code, 302)
     self.assertEqual(response.url, reverse('simulation.upload'))
     time.sleep(0.1)
     self.assertEqual(UploadJob.objects.count(), upload_jobs_count + 1)
     upload_job = UploadJob.objects.get(name='output_file')
     self.assertEqual(upload_job.historical, False)
Esempio n. 20
0
    def test_create_update_and_delete_project(self):
        create_project_url = reverse(create_project_handler)
        _check_login(self, create_project_url)

        # check validation of bad requests
        response = self.client.post(create_project_url, content_type='application/json', data=json.dumps({'bad_json': None}))
        self.assertEqual(response.status_code, 400)

        response = self.client.post(create_project_url, content_type='application/json', data=json.dumps({'form': {'missing_name': True}}))
        self.assertEqual(response.status_code, 400)

        # send valid request to create project
        response = self.client.post(create_project_url, content_type='application/json', data=json.dumps(
            {'name': 'new_project', 'description': 'new project description', 'genomeVersion': '38'}
        ))
        self.assertEqual(response.status_code, 200)

        # check that project was created
        new_project = Project.objects.filter(name='new_project')
        self.assertEqual(len(new_project), 1)
        self.assertEqual(new_project[0].description, 'new project description')
        self.assertEqual(new_project[0].genome_version, '38')

        project_guid = new_project[0].guid
        self.assertSetEqual(set(response.json()['projectsByGuid'].keys()), {project_guid})

        # update the project
        update_project_url = reverse(update_project_handler, args=[project_guid])
        response = self.client.post(update_project_url, content_type='application/json', data=json.dumps(
            {'description': 'updated project description'}
        ))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json()['projectsByGuid'][project_guid]['description'], 'updated project description')
        self.assertEqual(Project.objects.get(guid=project_guid).description, 'updated project description')

        # genome version should not update
        response = self.client.post(update_project_url, content_type='application/json', data=json.dumps(
            {'genomeVersion': '37'}
        ))
        self.assertEqual(response.json()['projectsByGuid'][project_guid]['genomeVersion'], '38')
        self.assertEqual(Project.objects.get(guid=project_guid).genome_version, '38')

        # delete the project
        delete_project_url = reverse(delete_project_handler, args=[project_guid])
        response = self.client.post(delete_project_url, content_type='application/json')

        self.assertEqual(response.status_code, 200)

        # check that project was deleted
        new_project = Project.objects.filter(name='new_project')
        self.assertEqual(len(new_project), 0)
Esempio n. 21
0
    def test_create_update_and_delete_gene_note(self):
        add_or_edit_url = reverse(add_or_edit_gene_note)
        delete_url = reverse(delete_gene_note, args=[1])
        _check_login(self, add_or_edit_url)

        # check validation of bad requests
        response = self.client.get(add_or_edit_url)
        self.assertTrue(response.json()['is_error'])

        response = self.client.get(add_or_edit_url, {'gene_id': 'ENSG00000008735', 'note_text': 'test note', 'note_id': 1})
        self.assertTrue(response.json()['is_error'])

        response = self.client.get(delete_url)
        self.assertTrue(response.json()['is_error'])

        # check that create works
        response = self.client.get(add_or_edit_url, {'gene_id': 'ENSG00000008735', 'note_text': 'test note'})

        self.assertEqual(response.status_code, 200)
        self.assertFalse(response.json()['is_error'])

        gene_notes = GeneNote.objects.all()
        self.assertEqual(len(gene_notes), 1)
        self.assertEqual(gene_notes[0].note, 'test note')
        self.assertEqual(gene_notes[0].gene_id, 'ENSG00000008735')
        self.assertEqual(gene_notes[0].user.username, 'test_user')
        initial_date_saved = gene_notes[0].date_saved

        # check that edit works
        response = self.client.get(add_or_edit_url, {'gene_id': 'ENSG00000008735', 'note_text': 'edited test note', 'note_id': 1})

        self.assertEqual(response.status_code, 200)
        self.assertFalse(response.json()['is_error'])

        gene_notes = GeneNote.objects.all()
        self.assertEqual(len(gene_notes), 1)
        self.assertEqual(gene_notes[0].note, 'edited test note')
        self.assertGreater(gene_notes[0].date_saved, initial_date_saved)

        # check that edit does not change the gene
        response = self.client.get(add_or_edit_url, {'gene_id': 'ENSG00000000001', 'note_text': 'test note', 'note_id': 1})
        self.assertEqual(response.json()['note']['gene_id'], 'ENSG00000008735')

        # check that delete works
        response = self.client.get(delete_url)

        self.assertEqual(response.status_code, 200)
        self.assertFalse(response.json()['is_error'])

        gene_notes = GeneNote.objects.all()
        self.assertEqual(len(gene_notes), 0)
Esempio n. 22
0
File: cal.py Progetto: WPI-LNL/lnldb
def generate_cal_json(queryset, from_date=None, to_date=None):
        if from_date and to_date:
            queryset = queryset.filter(
                datetime_start__range=(
                    timestamp_to_datetime(from_date) + datetime.timedelta(-30),
                    timestamp_to_datetime(to_date)
                )
            )
        elif from_date:
            queryset = queryset.filter(
                datetime_start__gte=timestamp_to_datetime(from_date)
            )
        elif to_date:
            queryset = queryset.filter(
                datetime_end__lte=timestamp_to_datetime(to_date)
            )
        objects_body = []
        for event in queryset:
            field = {
                "id": event.cal_guid(),
                "title": conditional_escape(event.cal_name()),
                "url": reverse('events:detail', args=[event.id]),
                "class": 'cal-status-' + slugify(event.status),
                "start": datetime_to_timestamp(event.cal_start() + datetime.timedelta(hours=-5)),
                "end": datetime_to_timestamp(event.cal_end() + datetime.timedelta(hours=-5))
            }
            objects_body.append(field)

        objects_head = {"success": 1, "result": objects_body}
        return json.dumps(objects_head)
Esempio n. 23
0
 def test_sso_url_https(self):
     response = self.client.get(reverse('django_auth_pubtkt.sso') + '?next=https://example.com')
     self.assertEqual(response.status_code, 302)
     # redirect url looks like '/login/?back=http%3A%2F%2Ftestserver%2F'
     url, querystring = response.url.split("?", 2)
     self.assertEqual(url, settings.TKT_AUTH_LOGIN_URL)
     self.assertEqual(querystring, 'haha=https%3A%2F%2Fexample.com')
    def test_saved_variant_data(self):
        url = reverse(saved_variant_data, args=['R0001_1kg'])
        _check_login(self, url)

        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        variants = response.json()['savedVariantsByGuid']
        self.assertSetEqual(set(variants.keys()), {'SV0000002_1248367227_r0390_100', 'SV0000001_2103343353_r0390_100'})

        variant = variants['SV0000001_2103343353_r0390_100']
        self.assertSetEqual(
            set(variant.keys()),
            {'variantId', 'variantGuid', 'xpos', 'ref', 'alt', 'chrom', 'pos', 'genomeVersion', 'liftedOverGenomeVersion',
             'liftedOverChrom', 'liftedOverPos', 'familyGuids', 'tags', 'functionalData', 'notes', 'clinvar',
             'originalAltAlleles', 'mainTranscript', 'genotypes', 'hgmd', 'transcripts', 'locusListGuids', 'populations',
             'predictions', 'rsid', 'genotypeFilters'}
        )
        self.assertSetEqual(set(variant['genotypes'].keys()), {'I000003_na19679', 'I000001_na19675', 'I000002_na19678'})

        # filter by family
        response = self.client.get('{}?families=F000002_2'.format(url))
        self.assertEqual(response.status_code, 200)

        self.assertSetEqual(set(response.json()['savedVariantsByGuid'].keys()), {'SV0000002_1248367227_r0390_100'})

        # filter by variant guid
        response = self.client.get('{}{}'.format(url, VARIANT_GUID))
        self.assertEqual(response.status_code, 200)

        self.assertSetEqual(set(response.json()['savedVariantsByGuid'].keys()), {VARIANT_GUID})

        # filter by invalid variant guid
        response = self.client.get('{}foo'.format(url))
        self.assertEqual(response.status_code, 404)
Esempio n. 25
0
def addeditorgs(request, org_id=None):
    """
    internal form for adding/editing an org
    Clients should not have access to this page. The accounts field autocomplete exposes ALL funds,
    and this form also allows the owner of the org to be changed without the email verification done
    by the org transfer form. Clients should use the much less confusing 'orgedit' view.
    """
    if not request.user.has_perm('events.view_org'):
            raise PermissionDenied
    context = {}
    if org_id:
        instance = get_object_or_404(Organization, pk=org_id)
        msg = "Edit Client"
    else:
        instance = None
        msg = "New Client"

    if request.method == 'POST':
        form = IOrgForm(request.user, request.POST, instance=instance)
        if form.is_valid():
            org = form.save()
            messages.add_message(request, messages.SUCCESS, 'Changes saved.')
            # return HttpResponseRedirect(reverse("home", kwargs={'msg':SUCCESS_MSG_ORG}))
            return HttpResponseRedirect(reverse('orgs:detail', kwargs={'org_id': org.pk}))
        else:
            context['form'] = form
            messages.add_message(request, messages.WARNING, 'Invalid Data. Please try again.')
    else:
        form = IOrgForm(request.user, instance=instance)
        context['form'] = form

    context['msg'] = msg

    return render(request, 'form_crispy.html', context)
Esempio n. 26
0
    def test_delete_mme_submission(self):
        url = reverse(delete_mme_submission, args=[INDIVIDUAL_GUID])
        _check_login(self, url)

        responses.add(responses.DELETE, 'http://localhost:9020/patient/delete', body='Failed request', status=400)
        responses.add(responses.DELETE, 'http://localhost:9020/patient/delete', status=200)

        response = self.client.post(url)
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.reason_phrase, 'Failed request')

        response = self.client.post(url)
        self.assertEqual(response.status_code, 200)
        response_json = response.json()
        self.assertEqual(
            response_json['individualsByGuid'][INDIVIDUAL_GUID]['mmeDeletedDate'][:10],
            datetime.today().strftime('%Y-%m-%d')
        )

        # Test proxy calls
        self.assertEqual(len(responses.calls), 2)
        self.assertEqual(responses.calls[1].request.url, 'http://localhost:9020/patient/delete')
        self.assertEqual(responses.calls[1].request.headers['X-Auth-Token'], 'abcd')
        self.assertEqual(responses.calls[1].request.headers['Accept'], 'application/vnd.ga4gh.matchmaker.v1.0+json')
        self.assertEqual(responses.calls[1].request.headers['Content-Type'],
                         'application/vnd.ga4gh.matchmaker.v1.0+json')
        self.assertEqual(responses.calls[1].request.body, json.dumps({'id': 'NA19675_1_01'}))

        # Test do not delete if already deleted
        response = self.client.post(url)
        self.assertEqual(response.status_code, 402)
        self.assertEqual(response.reason_phrase, 'Matchmaker submission has already been deleted for NA19675_1')
Esempio n. 27
0
def hours_prefill_self(request, id):
    event = get_object_or_404(BaseEvent, pk=id)
    if not event.ccinstances.exists():
        raise PermissionDenied
    if event.hours.filter(user=request.user).exists():
        messages.add_message(request, messages.ERROR, 'You already have hours for this event.')
        return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
    if timezone.now() < min(event.ccinstances.values_list('setup_start', flat=True)):
        messages.add_message(request, messages.ERROR, 'You cannot use this feature until the event setup has started.')
        return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
    if timezone.now() > event.datetime_end + timedelta(hours=3):
        messages.add_message(request, messages.ERROR, 'This feature is disabled 3 hours after the event end time.')
        return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
    Hours.objects.create(event=event, user=request.user)
    messages.add_message(request, messages.SUCCESS, 'You have been added as crew for this event.')
    return HttpResponseRedirect(reverse('events:detail', args=(event.id,)))
Esempio n. 28
0
def orgedit(request, id):
    context = {}
    if request.user.is_superuser:
        orgs = Organization.objects.all()
    else:
        orgs = Organization.objects.filter(user_in_charge=request.user)

    org = get_object_or_404(orgs, pk=id)
    msg = "> Modify Organization"
    context['msg'] = msg

    if request.method == 'POST':
        formset = ExternalOrgUpdateForm(request.POST, instance=org)
        if formset.is_valid():
            formset.save()
            return HttpResponseRedirect(reverse('orgs:list'))

        else:
            context['formset'] = formset
    else:

        formset = ExternalOrgUpdateForm(instance=org)

        context['formset'] = formset

    return render(request, 'mycrispy.html', context)
    def test_update_variant_tags(self):
        variant_tags = VariantTag.objects.filter(saved_variant__guid=VARIANT_GUID)
        self.assertSetEqual({"Review", "Tier 1 - Novel gene and phenotype"}, {vt.variant_tag_type.name for vt in variant_tags})
        variant_functional_data = VariantFunctionalData.objects.filter(saved_variant__guid=VARIANT_GUID)
        self.assertSetEqual({"Biochemical Function", "Genome-wide Linkage"}, {vt.functional_data_tag for vt in variant_functional_data})
        self.assertSetEqual({"A note", "2"}, {vt.metadata for vt in variant_functional_data})

        update_variant_tags_url = reverse(update_variant_tags_handler, args=[VARIANT_GUID])
        _check_login(self, update_variant_tags_url)

        response = self.client.post(update_variant_tags_url, content_type='application/json', data=json.dumps({
            'tags': [{'tagGuid': 'VT1708633_2103343353_r0390_100', 'name': 'Review'}, {'name': 'Excluded'}],
            'functionalData': [
                {'tagGuid': 'VFD0000023_1248367227_r0390_10', 'name': 'Biochemical Function', 'metadata': 'An updated note'},
                {'name': 'Bonferroni corrected p-value', 'metadata': 0.05}
            ]
        }))
        self.assertEqual(response.status_code, 200)

        tags = response.json()['savedVariantsByGuid'][VARIANT_GUID]['tags']
        self.assertEqual(len(tags), 2)
        self.assertSetEqual({"Review", "Excluded"}, {vt['name'] for vt in tags})
        self.assertSetEqual({"Review", "Excluded"}, {vt.variant_tag_type.name for vt in VariantTag.objects.filter(saved_variant__guid=VARIANT_GUID)})

        functionalData = response.json()['savedVariantsByGuid'][VARIANT_GUID]['functionalData']
        self.assertEqual(len(functionalData), 2)
        self.assertSetEqual({"Biochemical Function", "Bonferroni corrected p-value"}, {vt['name'] for vt in functionalData})
        self.assertSetEqual({"An updated note", "0.05"}, {vt['metadata'] for vt in functionalData})
        variant_functional_data = VariantFunctionalData.objects.filter(saved_variant__guid=VARIANT_GUID)
        self.assertSetEqual({"Biochemical Function", "Bonferroni corrected p-value"}, {vt.functional_data_tag for vt in variant_functional_data})
        self.assertSetEqual({"An updated note", "0.05"}, {vt.metadata for vt in variant_functional_data})
Esempio n. 30
0
    def test_update_mme_result_status(self):
        url = reverse(update_mme_result_status, args=[RESULT_STATUS_GUID])
        _check_login(self, url)

        response = self.client.post(url, content_type='application/json', data=json.dumps({
            'matchmakerResultGuid': RESULT_STATUS_GUID,
            'comments': 'test comment',
            'deemedIrrelevant': False,
            'flagForAnalysis': True,
        }))

        self.assertEqual(response.status_code, 200)
        response_json = response.json()
        self.assertDictEqual(response_json, {'mmeResultsByGuid': {RESULT_STATUS_GUID: {
            'matchStatus': {
                'matchmakerResultGuid': RESULT_STATUS_GUID,
                'comments': 'test comment',
                'weContacted': False,
                'hostContacted': True,
                'deemedIrrelevant': False,
                'flagForAnalysis': True,
                'createdDate': '2019-02-12T18:43:56.358Z',
            },
        }}})

        result_model = MatchmakerResult.objects.get(guid=RESULT_STATUS_GUID)
        self.assertEqual(result_model.comments, 'test comment')
Esempio n. 31
0
 def geoapp_detail_url(self, geoapp):
     return reverse('geoapp_detail', args=(geoapp.id,))
Esempio n. 32
0
 def get_model_url(self, model, name, *args, **kwargs):
     return reverse(
         '%s:%s_%s_%s' % (self.admin_site.app_name, model._meta.app_label,
                          model._meta.model_name, name),
         args=args, kwargs=kwargs, current_app=self.admin_site.name)
    def test_diplomacy(self):
        capability = Capability.objects.get(organization__id=102,
                                            type=Capability.DIPLOMACY,
                                            applying_to_id=101)

        response = self.client.post(reverse(
            'organization:diplomacy_capability',
            kwargs={
                'capability_id': capability.id,
                'target_organization_id': 105
            }),
                                    data={'target_relationship': 'friendship'},
                                    follow=True)
        self.assertRedirects(
            response,
            Organization.objects.get(id=102).get_absolute_url())

        relationship = OrganizationRelationship.objects.get(
            from_organization_id=101,
            to_organization_id=105,
        )
        self.assertEqual(relationship.desired_relationship, 'friendship')

        self.client.get(reverse('character:activate', kwargs={'char_id': 7}),
                        follow=True)

        capability = Capability.objects.get(organization__id=106,
                                            type=Capability.DIPLOMACY,
                                            applying_to_id=105)

        response = self.client.get(capability.get_absolute_url())
        self.assertEqual(response.status_code, 200)

        response = self.client.get(
            reverse('organization:diplomacy_capability',
                    kwargs={
                        'capability_id': capability.id,
                        'target_organization_id': 101
                    }))
        self.assertEqual(response.status_code, 200)

        response = self.client.post(reverse(
            'organization:diplomacy_capability',
            kwargs={
                'capability_id': capability.id,
                'target_organization_id': 101
            }),
                                    data={'target_relationship': 'accept'},
                                    follow=True)

        self.assertRedirects(
            response,
            Organization.objects.get(id=106).get_absolute_url())

        relationship = OrganizationRelationship.objects.get(
            from_organization_id=101,
            to_organization_id=105,
        )
        self.assertEqual(relationship.relationship, 'friendship')
        self.assertEqual(relationship.desired_relationship, None)

        relationship = OrganizationRelationship.objects.get(
            from_organization_id=105,
            to_organization_id=101,
        )
        self.assertEqual(relationship.relationship, 'friendship')
        self.assertEqual(relationship.desired_relationship, None)
Esempio n. 34
0
 def get_success_url(self):
     return reverse('accounts:detail', args=(self.object.id, ))
Esempio n. 35
0
 def get_absolute_url(self):
     return reverse("brand_detail", kwargs={"brand_id": self.id})
Esempio n. 36
0
 def map_list_url(self):
     return self.add_limit_settings(reverse('maps_browse'))
Esempio n. 37
0
 def dataset_detail_url(self, layer):
     return reverse('dataset_detail', args=(layer.alternate,))
Esempio n. 38
0
 def get_activate_link(cls):
     return reverse("admin_front_list_activate_view")
Esempio n. 39
0
 def map_detail_url(self, map):
     return reverse('map_detail', args=(map.id,))
Esempio n. 40
0
 def get_edit_link(cls, object_id):
     return reverse("admin_front_list_edit_link_view",
                    kwargs={"pk": object_id})
Esempio n. 41
0
 def get_object_detail_link(self):
     return reverse("admin_front_list_details_view", kwargs={"pk": self.pk})
Esempio n. 42
0
 def run_link(self, obj):
     return mark_safe('<a href="%s">Run</a>' %
                      reverse('admin:inspection_run', args=(obj.pk, )))
Esempio n. 43
0
 def geoapp_list_url(self):
     return self.add_limit_settings(reverse('apps_browse'))
Esempio n. 44
0
 def dataset_list_url(self):
     return self.add_limit_settings(reverse('dataset_browse'))
Esempio n. 45
0
 def get_success_url(self, form_name=None):
     return reverse('user_profile:user_profile_page',
                    kwargs={"username": self.kwargs.get("username")})
Esempio n. 46
0
 def get_absolute_url(self):
     return reverse("category_detail", kwargs={"category_slug": self.slug})
Esempio n. 47
0
 def get_success_url(self):
     return reverse('accounts:detail', args=[self.user.pk])
Esempio n. 48
0
 def test_create_anon(self):
     response = self.client.get(reverse('course-create-view'))
     self.assertEqual(response.status_code, 302)
     self.assertEqual(
         response.url, "/accounts/login/?next=/course/create/")
Esempio n. 49
0
 def document_detail_url(self, document):
     return reverse('document_detail', args=(document.id,))
Esempio n. 50
0
 def model_admin_url(self, name, *args, **kwargs):
     return reverse(
         "%s:%s_%s_%s" % (self.admin_site.app_name, self.opts.app_label,
                          self.model_name, name), args=args, kwargs=kwargs)
Esempio n. 51
0
 def get_absolute_url(self):
     return reverse("product_detail", kwargs={"product_slug": self.slug})
Esempio n. 52
0
def get_presentations_staff(user):
    """
    Displays the presentations for a staff member
    Only show sets, not individual presentations.

    :param user:
    :return:
    """
    if not user.is_authenticated:
        return False
    # check if not student
    if not user.groups.exists():
        return False
    ts = get_timeslot()
    try:
        options = ts.presentationoptions
    except PresentationOptions.DoesNotExist:
        return "The presentations are not yet planned."  # hide if no options yet.

    if options.Public or get_timephase_number() == 7:
        # check if trackhead has presentations. Show set only.
        html = ''
        if is_track_head(user):
            try:
                sets = options.presentationsets.filter(
                    Track__in=user.tracks.all())
            except PresentationSet.DoesNotExist:
                return "The presentations for your track are not yet planned"
            if sets.exists():
                html += '<p>Your tracks presentations are starting on:</p><ul>'
                for set in sets:
                    start = timezone.localtime(
                        set.DateTime).strftime("%A %d %B %H:%M")
                    room = set.PresentationRoom.room_link()
                    html += "<li> {}: {} in {} </li>".format(
                        set.Track, start, room)
                html += "</ul>"
            else:
                html += "<p>You do not have presentations for your track to attend</p>"

        # check if user has presentations, for responsible and assistants. Show each presentation.
        t = PresentationTimeSlot.objects.filter(
            (Q(Distribution__Proposal__ResponsibleStaff=user)
             | Q(Distribution__Proposal__Assistants=user))
            & Q(Presentations__PresentationOptions=options)).distinct()
        if t.exists():
            html += '<p>Your presentations as supervisor are:</p><ul>'
            for presentation in t:
                start = timezone.localtime(
                    presentation.DateTime).strftime("%A %d %B %H:%M")
                room = presentation.Presentations.PresentationRoom.room_link()
                html += "<li> {} at {} in {} </li>".format(
                    presentation.Distribution.Student.usermeta.
                    get_nice_fullname(), start, room)
            html += "</ul>"
        else:
            html += "<p>You do not have any presentations to attend as supervisor.</p>"

        # Assessors / type1
        if user.assessors.filter(PresentationOptions=options).exists():
            html += '<p>You are assessor for presentations starting on:</p><ul>'
            for set_in in options.presentationsets.all():
                if user in set_in.Assessors.all():
                    start = timezone.localtime(
                        set_in.DateTime).strftime("%A %d %B %H:%M")
                    room = set_in.PresentationRoom.room_link()
                    html += "<li>" + str(set_in.Track) + ": " + str(
                        start) + " in " + str(room) + "</li>"
            html += "</ul>"

        # Presentation assessor / ESA / Type 7
        if user.presentation_assessors.filter(
                PresentationOptions=options).exists():
            html += '<p>You are presentation assessor for presentations starting on:</p><ul>'
            for set_in in options.presentationsets.all():
                if user in set_in.PresentationAssessors.all():
                    start = timezone.localtime(
                        set_in.DateTime).strftime("%A %d %B %H:%M")
                    room = set_in.PresentationRoom.room_link()
                    html += "<li>" + str(set_in.Track) + ": " + str(
                        start) + " in " + str(room) + "</li>"
            html += "</ul>"

        html += '<a href="{}" class ="button primary">{}</a>'
        url = reverse('presentations:presentationscalendarown')
        title = "Presentations"
        st = format_html(html, url, title)
        return st
    else:
        return "Your presentation time slot will appear here when the planning becomes public."
Esempio n. 53
0
 def test_delete_anon(self):
     url = reverse('course-delete-view', args=[self.sandbox_course.pk])
     response = self.client.get(url)
     self.assertEqual(response.status_code, 302)
     self.assertEqual(response.url, "/accounts/login/?next=" + url)
Esempio n. 54
0
def cdelete(request, c_id):
    c = get_object_or_404(Choice, id=c_id)
    c.delete()
    return HttpResponseRedirect(reverse('vote:detail', args=(c.q.id, )))
Esempio n. 55
0
 def get_absolute_url(self):
     return reverse('content:post_detail', kwargs={'slug': self.slug})
Esempio n. 56
0
 def get_admin_url(self, name, *args, **kwargs):
     return reverse('%s:%s' % (self.admin_site.app_name, name), args=args, kwargs=kwargs)
Esempio n. 57
0
    def _match_view(self, request, object_id, extra_context=None):
        """
        The 'match list' view for this model.
        """
        from django.contrib.admin.views.main import ERROR_FLAG

        if self.match_parent_model is None:
            match_parent_sitemodel = self
        else:
            match_parent_sitemodel = self.admin_site._registry[
                self.match_parent_model]

        match_child_sitemodel = self.admin_site._registry[
            self.match_child_model]

        opts = match_child_sitemodel.model._meta

        # opts = self.model._meta
        app_label = opts.app_label
        if not self.has_permission(request, 'match'):
            raise PermissionDenied

        match_list_display = self.match_list_display
        match_list_display_links = match_child_sitemodel.get_list_display_links(
            request, match_list_display)
        match_list_filter = match_child_sitemodel.get_list_filter(request)
        match_top_filters = match_child_sitemodel.get_top_filters(request)
        match_date_hierarchy = self.match_date_hierarchy
        match_list_search_fields = self.match_list_search_fields
        match_list_select_related = self.match_list_select_related
        match_list_per_page = self.match_list_per_page
        match_list_max_show_all = self.match_list_max_show_all
        match_list_editable = self.match_list_editable

        to_field = request.POST.get(TO_FIELD_VAR,
                                    request.GET.get(TO_FIELD_VAR))

        obj = self.get_object(request, unquote(object_id), to_field)

        if not self.has_permission(request, 'match', obj):
            raise PermissionDenied

        if obj is None:
            return self._get_obj_does_not_exist_redirect(
                request, opts, object_id)

        MatchList = self.get_matchlist(request)
        try:
            cl = MatchList(request, match_list_display,
                           match_list_display_links, match_list_filter,
                           match_top_filters, match_date_hierarchy,
                           match_list_search_fields, match_list_select_related,
                           match_list_per_page, match_list_max_show_all,
                           match_list_editable, match_parent_sitemodel,
                           object_id, match_child_sitemodel,
                           self.get_sortable_by(request))
        except IncorrectLookupParameters:
            # Wacky lookup parameters were given, so redirect to the main
            # changelist page, without parameters, and pass an 'invalid=1'
            # parameter via the query string. If wacky parameters were given
            # and the 'invalid=1' parameter was already in the query string,
            # something is screwed up with the database, so display an error
            # page.
            if ERROR_FLAG in request.GET.keys():
                return SimpleTemplateResponse('admin/invalid_setup.html', {
                    'title': _('Database error'),
                })
            return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')

        # If we're allowing changelist editing, we need to construct a formset
        # for the changelist given all the fields to be edited. Then we'll
        # use the formset to validate/process POSTed data.
        formset = cl.formset = None

        # Handle POSTed bulk-edit data.
        if request.method == 'POST' and '_cancel' in request.POST:
            info = self.model._meta.app_label, self.model._meta.model_name
            return HttpResponseRedirect(
                reverse('common:%s_%s_change' % info, args=[obj.id]))

        if request.method == 'POST' and '_save' in request.POST:
            FormSet = self.get_matchlist_formset(request)
            formset = cl.formset = FormSet(request.POST,
                                           request.FILES,
                                           queryset=self.get_queryset(request))
            if formset.is_valid():
                matches = self.build_matches(formset.forms)
                try:
                    self.save_matches(obj, matches)
                    msg = "Matched successfully."
                    self.message_user(request, msg, messages.SUCCESS)
                except ValidationError as ex:
                    for message in ex.messages:
                        self.message_user(request, message, messages.ERROR)

            return HttpResponseRedirect(request.get_full_path())

        # Handle GET -- construct a formset for display.
        elif cl.list_editable:
            FormSet = self.get_matchlist_formset(request)
            formset = cl.formset = FormSet(queryset=cl.result_list)

        ModelForm = self.get_form(request, obj)

        form = ModelForm(instance=obj)
        formsets, inline_instances = self._create_formsets(request,
                                                           obj,
                                                           change=True)

        adminForm = helpers.AdminForm(
            form,
            list(self.get_match_parent_fieldsets(request, obj)),
            self.get_prepopulated_fields(request, obj),
            self.get_match_parent_readonly_fields(request, obj),
            model_admin=self)
        media = self.media + adminForm.media

        # Build the list of media to be used by the formset.
        if formset:
            media += self.media + formset.media
        else:
            media += self.media

        action_form = None

        selection_note_all = ungettext('%(total_count)s selected',
                                       'All %(total_count)s selected',
                                       cl.result_count)

        # Possible Duplicate of lines 307-310???
        # ModelForm = self.get_form(request, obj)
        # form = ModelForm(instance=obj)
        # formsets, inline_instances = self._create_formsets(request, obj, change=True)

        context = dict(
            self.admin_site.each_context(request),
            title=_('Change %s') % force_text(opts.verbose_name),
            adminform=adminForm,
            change=True,
            object_id=object_id,
            original=obj,
            save_as=False,
            change_actions=False,
            show_save=False,
            show_save_and_continue=False,
            has_add_permission=False,
            has_change_permission=True,
            has_delete_permission=False,
            is_popup=(IS_POPUP_VAR in request.POST
                      or IS_POPUP_VAR in request.GET),
            to_field=to_field,
            media=media,
            inline_admin_formsets=[],
            errors=helpers.AdminErrorList(form, formsets),
            preserved_filters=self.get_preserved_filters(request),
            module_name=force_text(opts.verbose_name_plural),
            selection_note=_('0 of %(cnt)s selected') %
            {'cnt': len(cl.result_list)},
            selection_note_all=selection_note_all %
            {'total_count': cl.result_count},
            cl=cl,
            opts=cl.opts,
            action_form=action_form,
            actions_on_top=self.actions_on_top,
            actions_on_bottom=self.actions_on_bottom,
            actions_selection_counter=self.actions_selection_counter,
        )
        context.update(self.get_model_extra_context(request))
        context.update(extra_context or {})

        request.current_app = self.admin_site.name

        return TemplateResponse(request, 'finance/match.html', context)
Esempio n. 58
0
 def document_list_url(self):
     return self.add_limit_settings(reverse('document_browse'))
Esempio n. 59
0
 def get_delete_link(cls):
     return reverse("admin_front_list_delete_view")
Esempio n. 60
0
 def url(self):
     base_url = reverse(self.url_name)
     if self.query:
         base_url = base_url + '?' + self.query
     return base_url