Exemplo n.º 1
0
def order(request):
    orderId = request.GET.get('orderId', None)
    if orderId is None:
        orderId = request.POST.get('orderId', None)
    if orderId is None:
        return _error(request, u'非法调用', u'参数错误')
    pay = request.POST.get('pay', None)
    pay = 'false' if pay is None or pay <> 'yes' else 'true'
    order = data.fetchOrderById(orderId)
    if order is None:
        return _error(request, u'非法调用', u'订单不存在')
    payRequest = auth.createPayRequestJson(order.prepay_id)
    orderAmounts = data.fetchOrderAmounts(order.batch.id) + 1
    wxConfigJson = auth.createWXConfigJson(
        request.get_raw_uri(),
        ['chooseWXPay', 'onMenuShareAppMessage', 'closeWindow'])
    shareUrl = '%s/r?id=%s' % (DOMAIN_URL, order.batch.id)
    context = RequestContext(
        request, {
            'order': order,
            'payRequest': SafeString(json.dumps(payRequest)),
            'orderAmounts': orderAmounts,
            'wxConfigJson': SafeString(json.dumps(wxConfigJson)),
            'shareUrl': shareUrl,
            'pay': pay
        })
    template = loader.get_template('web/order.html')
    return HttpResponse(template.render(context))
Exemplo n.º 2
0
def delete(request, type, id):
    error = False
    obj = False
    form = ''
    prompt = ''
    editable = [
        'Sample', 'Piece', 'Action', 'General', 'Local', 'Local_Attachment',
        'Design', 'Design_Item', 'Design_Object_Attachment'
    ]
    caller = 'Delete'
    if type not in editable:
        error = "%s not editable or does not exist" % type
    if type == 'Action' or type == 'Sample' or type == 'Design' or type == 'Design_Item' or type == 'Design_Object_Attachment':
        if type == 'Action':
            name = eval(type + ".objects.get(id=%s)" % id).action_type.name
        if type == 'Sample' or type == 'Design' or type == 'Design_Item' or type == 'Design_Object_Attachment':
            name = eval(type + ".objects.get(id=%s)" % id).name
        if name == 'None' or name == 'Created':
            error = "%s %s is not deletable" % (type, name)
    if not error:
        obj = eval(type + ".objects.get(id=%s)" % id)
        if request.POST:
            try:
                obj.delete()
            except models.ProtectedError:
                error = "%s %s is not deletable since it is in usage by another object" % (
                    type, name)
                context = RequestContext(
                    request, {
                        'obj': obj,
                        'error': error,
                        'type': type.replace("_", " "),
                        'caller': caller,
                        'prompt': SafeString(prompt)
                    }).flatten()
                return render(request, 'sample_database/edit.html', context)

            continue_url = request.GET.get('cont')
            if continue_url:
                return redirect(continue_url)
            else:
                return redirect(reverse('DB:home'))
        else:
            children_type = [
                el for el in dir(obj) if len(re.findall("_set$", el))
            ]
            direct = 0
            for child_type in children_type:
                child = getattr(obj, child_type).all()
                direct += len(child)
            prompt = "Are you sure you want to delete this and %i direct children?<br><br><b>The action is permanent!</b>" % direct
    context = RequestContext(
        request, {
            'obj': obj,
            'error': error,
            'type': type.replace("_", " "),
            'caller': caller,
            'prompt': SafeString(prompt)
        }).flatten()
    return render(request, 'sample_database/edit.html', context)
Exemplo n.º 3
0
    def render(self, name, value, attrs=None):
        loc_fields = [[item.id, item.fields]
                      for item in models.Service.objects.all()]
        i_field = {}
        for idx, fields in loc_fields:
            i_field[idx] = []
            for field in fields:
                print field
                print '_________________________----'
                if field['location'] == True:
                    i_field[idx].append(field)

        print i_field

        if value == {}:
            value = []
        context = {
            'name': name,
            'value': value,
            'js_string': SafeString(json.dumps(value)),
            'countries': SafeString(json.dumps(COUNTRY_CHOICES)),
            'fields': SafeString(json.dumps(self.fields)),
            'loc_fields': SafeString(json.dumps(i_field))
        }
        return mark_safe(render_to_string(self.template_name, context))
Exemplo n.º 4
0
    def post(self,request, *args, **kwargs):
        obj = BlastCalculatedPeptide.objects.filter(pk=kwargs["pk"])[:1]
        if not obj:
            return self.error("Blast pk is not valid")
        obj = obj[0]

        data = request.GET.get("data")

        if data == "prot-list":
            l = BlastCalculatedPeptide.objects.filter(blast=obj.blast,gi=obj.gi).order_by("calculatedpeptide__analyse__pk","calculatedpeptide__pk","-score")
            #l = BlastCalculatedPeptide.objects.filter(blast=obj.blast,gi=obj.gi).order_by("-score")
            rows = []
            for u in l:
                rows.append({
                    "cal_pk" : u.calculatedpeptide.pk,
                    "ana_pk" : u.calculatedpeptide.analyse.pk,
                    "ana_name" : u.calculatedpeptide.analyse.__unicode__(),
                    "score" : u.score,
                    "e_value" : u.e_value,
                    "sequence_match" : SafeString(u.sequence_match),
                    "sequence_real" : SafeString(u.sequence_real),
                    "sequence_aa" : u.calculatedpeptide.sequence_aa,
                    "cal_url" : u.calculatedpeptide.get_absolute_url(),
                    "ana_url" : u.calculatedpeptide.analyse.get_absolute_url(),
                })
            self.data.update({"rows":rows})
        else:
            return self.error("unknow value %s for param data" % data)

        return super(Ajax_BlastPepRecieverView,self).post(request,*args,**kwargs)
Exemplo n.º 5
0
def confirm_email_change(request: HttpRequest, confirmation_key: str) -> HttpResponse:
    try:
        email_change_object = get_object_from_key(confirmation_key, Confirmation.EMAIL_CHANGE)
    except ConfirmationKeyException as exception:
        return render_confirmation_key_error(request, exception)

    new_email = email_change_object.new_email
    old_email = email_change_object.old_email
    user_profile = email_change_object.user_profile

    if user_profile.realm.email_changes_disabled and not user_profile.is_realm_admin:
        raise JsonableError(_("Email address changes are disabled in this organization."))

    do_change_user_delivery_email(user_profile, new_email)

    context = {'realm_name': user_profile.realm.name, 'new_email': new_email}
    language = user_profile.default_language
    send_email('zerver/emails/notify_change_in_email', to_emails=[old_email],
               from_name=FromAddress.security_email_from_name(user_profile=user_profile),
               from_address=FromAddress.SUPPORT, language=language,
               context=context,
               realm=user_profile.realm)

    ctx = {
        'new_email_html_tag': SafeString(f'<a href="mailto:{escape(new_email)}">{escape(new_email)}</a>'),
        'old_email_html_tag': SafeString(f'<a href="mailto:{escape(old_email)}">{escape(old_email)}</a>'),

    }
    return render(request, 'confirmation/confirm_email_change.html', context=ctx)
def load_carousel(context, section, template, carousel_id=None):
    _func_name = 'load_carousel'
    _log_msg = f'Template Tag {_func_name}'

    request = context['request']
    page = context['page']
    language = getattr(request, 'LANGUAGE_CODE', '')

    if carousel_id:
        return _load_carousel_by_id(carousel_id=carousel_id,
                                    template=template,
                                    lang=language,
                                    log_msg=_log_msg,
                                    func_name=_func_name)
    else:
        if not section: return SafeString('')

        page_carousel = page.get_carousels().first()

        # page_carousel = PageCarousel.objects.filter(section=section,
        # is_active=True,
        # carousel__is_active=True,
        # page__webpath=context['webpath']).\
        # first()
        if not page_carousel:  # pragma: no cover
            _msg = '{} cannot find carousel in page {} and section {}'\
                   .format(_func_name, page, section)
            logger.error(_msg)
            return SafeString('')

        carousel = page_carousel.carousel
        carousel_items = carousel.get_items(lang=language)
        data = {'carousel_items': carousel_items}
        return handle_faulty_templates(template, data, name=_func_name)
Exemplo n.º 7
0
def vote(request, option_id):
    context = dict()
    context[
        'auth'] = request.user.is_authenticated  # нужно для отображения меню
    context['voting'] = Voting.objects.get(
        id=option_id)  # добавление вопроса по его id
    context['options'] = Option.objects.filter(
        voting_id=option_id)  # добавление всех его вариантов ответа
    context['option_id'] = option_id  # номер вопроса
    data_t = ThemeBD.objects.in_bulk()
    lent = len(data_t)
    context['theme_flag'] = (data_t[lent].Theme)

    labels = []
    data = []

    for option in context['options']:
        labels.append(option.text)
        data.append(option.vote_count())

    context['labels'] = SafeString(json.dumps(labels))
    context['data'] = SafeString(json.dumps(data))

    single_vote(request)
    return render(request, 'vote.html', context)
Exemplo n.º 8
0
def clientRequest(request):
    clientOrdersObj = AmazeUsersOrders.objects.filter(
        userInstance=request.user)
    ordersInBox = []
    outForDeliveries = []
    incomingDeliveries = []
    previousDeliveries = []

    for i in clientOrdersObj:

        data = {
            "orderId": i.orderId,
            "orderName": i.orderName,
            "orderCost": i.orderCost,
            "contact": i.contact,
            "orderStatus": i.orderStatus,
            "orderDate": str(i.orderDate)
        }

        if (i.orderStatus == "InBox"):
            ordersInBox.append(data)
        elif (i.orderStatus == "OutForDelivery"):
            outForDeliveries.append(data)
        elif (i.orderStatus == "FutureOrder"):
            incomingDeliveries.append(data)
        else:
            previousDeliveries.append(data)

    context = {
        "ordersInBox": SafeString(ordersInBox),
        "outForDeliveries": SafeString(outForDeliveries),
        "incomingDeliveries": SafeString(incomingDeliveries),
        "previousDeliveries": SafeString(previousDeliveries)
    }
    return render(request, 'amazeUserPage.html', context)
Exemplo n.º 9
0
def fullcalendar_config():
    events = CalendarEvent.objects.all()
    final_config = SafeString("""{  timeFormat: "H:mm",
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: '',
                },
                allDaySlot: false,
                locale: 'cs',
                firstDay: 1,
                slotMinutes: 15,
                defaultEventMinutes: 30,
                minTime: 8,
                maxTime: 20,
                editable: false,
                eventClick: function(event, jsEvent, view) {
                    
                },
                events: [
            """)
    for event in events:
        final_config += SafeString("{" + "title:" +
                                   "'{}'".format(event.title) + ",")
        final_config += SafeString(
            "start:" +
            "'{}-{}T{}'".format(event.start.year, event.start.strftime(
                "%m-%d"), event.start.strftime("%H:%M:%S")) + ",")
        final_config += SafeString(
            "end:" +
            "'{}-{}T{}'".format(event.end.year, event.end.strftime("%m-%d"),
                                event.end.strftime("%H:%M:%S")) + ",},")
    final_config += SafeString("],}")

    return final_config
Exemplo n.º 10
0
def warriorRequest(request):
    warriorOrdersObj = AmazeWarriorsOrders.objects.filter(
        userInstance=request.user)
    x = []
    z = []
    print(warriorOrdersObj)
    for i in warriorOrdersObj:
        print(i)
        y = i.orderId
        print(y)
        if (y.orderStatus == "OutForDelivery"):
            data = {
                "address": y.orderAddress,
                "contact": y.contact,
                "status": y.orderStatus,
                "deliveryId": i.id,
                "orderDate": str(y.orderDate)
            }
            x.append(data)
        elif (y.orderStatus == "Delivered"):
            data = {
                "address": y.orderAddress,
                "contact": y.contact,
                "status": y.orderStatus,
                "deliveryId": i.id,
                "orderDate": str(y.orderDate)
            }
            z.append(data)

    context = {
        "outForDeliveries": SafeString(x),
        "previousDeliveries": SafeString(z)
    }

    return render(request, 'amazeWarriorPage.html', context)
Exemplo n.º 11
0
 def post(self, request, *args, **kwargs):
     form = self.get_form()
     if form.is_valid():
         if request.user.is_authenticated:
             contact_name = request.user.get_full_name()
             contact_email = request.user.email
         else:
             contact_name = form.cleaned_data.get('name')
             contact_email = form.cleaned_data.get('email')
         contact_message = "{name} {email}: ".format(name=contact_name,
                                                     email=contact_email)
         contact_message += "<br>{0}".format(
             SafeString(form.cleaned_data.get('message')))
         subject = form.cleaned_data.get('subject')
         msg = EmailMessage(
             subject,
             SafeString(contact_message),
             contact_email,
             [
                 '*****@*****.**',
             ],
         )
         msg.content_subtype = "html"
         msg.send()
         messages.success(request, _('Повідомлення успішно відправлено'))
         return self.form_valid(form)
     else:
         return self.form_invalid(form)
Exemplo n.º 12
0
def detail(request, the_slug):
    try:
        blog_item = BlogEntry.objects.get(slug=the_slug)
    except BlogEntry.DoesNotExist:
        raise Http404('That blog article doesn\'t exist')
    doneSafeString = False
    image_list = BlogImage.objects.filter(post=blog_item)
    codesnippet_list = BlogCodeSnippet.objects.filter(post=blog_item)
    for image in image_list:
        doneSafeString = True
        blog_item.body = SafeString(
            blog_item.body.replace(
                image.anchor, "<img src=\"" + image.image.url + "\" alt=\"" +
                image.caption + "\">" + "\n" + image.caption + "\n"))
    for codesnippet in codesnippet_list:
        doneSafeString = True
        if bool(codesnippet.caption):
            blog_item.body = SafeString(
                blog_item.body.replace(
                    codesnippet.anchor,
                    "<div class=\"callout\"><code>" + codesnippet.caption +
                    "</code><pre id=\"" + codesnippet.anchor + "\">" +
                    codesnippet.CodeSnippet + "</pre></div>"))
        else:
            blog_item.body = SafeString(
                blog_item.body.replace(
                    codesnippet.anchor,
                    "<div class=\"callout\"><pre id=\"" + codesnippet.anchor +
                    "\">" + codesnippet.CodeSnippet + "</pre></div>"))
    if not (doneSafeString):
        blog_item.body = SafeString(blog_item.body)
    return render(request, "blogitem.html", {
        "story": blog_item,
        "images": image_list
    })
Exemplo n.º 13
0
def verify_email_generate(user):
    hashin_mail = "*****@*****.**"
    user_mail = user['email']
    name = user['username']

    message = MIMEMultipart("alternative")
    message["Subject"] = "Verify your account"
    message["From"] = hashin_mail
    message["To"] = user_mail

    html_file = open("message.html", "r").read()
    text_file = open("message.txt", "r").read()

    link = "http://*****:*****@gmail.com", "*******")
        smtp.sendmail(hashin_mail, user_mail, message.as_string())
    return sec_token
Exemplo n.º 14
0
def index(request):
    latest_blog_list = BlogEntry.objects.filter(
        posted__lte=timezone.now()).order_by('-posted')
    for story in latest_blog_list:
        doneSafeString = False
        image_list = BlogImage.objects.filter(post=story)
        codesnippet_list = BlogCodeSnippet.objects.filter(post=story)
        for image in image_list:
            doneSafeString = True
            story.body = SafeString(
                story.body.replace(
                    image.anchor,
                    "<img src=\"" + image.image.url + "\" alt=\"" +
                    image.caption + "\">" + "\n" + image.caption + "\n"))
        for codesnippet in codesnippet_list:
            doneSafeString = True
            if bool(codesnippet.caption):
                story.body = SafeString(
                    story.body.replace(
                        codesnippet.anchor,
                        "<div class=\"callout\"><code>" + codesnippet.caption +
                        "</code><pre id=\"" + codesnippet.anchor + "\">" +
                        codesnippet.CodeSnippet + "</pre></div>"))
            else:
                story.body = SafeString(
                    story.body.replace(
                        codesnippet.anchor,
                        "<div class=\"callout\"><pre id=\"" +
                        codesnippet.anchor + "\">" + codesnippet.CodeSnippet +
                        "</pre></div>"))
        if not (doneSafeString):
            story.body = SafeString(story.body)
    return render(request, "blog.html", {"latest_blogs": latest_blog_list})
Exemplo n.º 15
0
def run_react_lambda(initial_props, initial_render_time: int = 0) -> LambdaResponse:
    start_time = time.time_ns()
    response = lambda_service.run_handler(initial_props)
    render_time = initial_render_time + int((time.time_ns() - start_time) / NS_PER_MS)

    pf = response["graphQLQueryToPrefetch"]
    if pf is not None:
        pf = GraphQLQueryPrefetchInfo(graphql=pf["graphQL"], input=pf["input"])

    lr = LambdaResponse(
        html=SafeString(response["html"]),
        is_static_content=response["isStaticContent"],
        http_headers=response["httpHeaders"],
        modal_html=SafeString(response["modalHtml"]),
        title_tag=SafeString(response["titleTag"]),
        meta_tags=SafeString(response["metaTags"]),
        script_tags=SafeString(response["scriptTags"]),
        status=response["status"],
        location=response["location"],
        traceback=response["traceback"],
        graphql_query_to_prefetch=pf,
        render_time=render_time,
    )

    if lr.status == 500:
        logger.error(lr.traceback)

    if lr.is_static_content:
        lr = lr._replace(html=DOCTYPE_HTML_TAG + lr.html)

    return lr
Exemplo n.º 16
0
    def get(cls, slug, language_code=None, request=None):
        """Returns the text's content, HTML-escaped unless it is
        itself HTML, and marked as a SafeString so that it can be used
        in templates immediately.

        If language_code is not given, it can be retrieved from the
        request, if that is given.

        If the text isn't found, a short text saying which slug should be
        entered into the admin interface is returned."""

        if language_code is None and request:
            language_code = getattr(request, 'LANGUAGE_CODE', None)

        search = {
            'slug': slug,
        }
        if language_code is not None:
            search['language'] = language_code

        texts = cls.objects.filter(**search)
        if texts.count() > 0:
            text = texts[0]
            if text.is_html:
                return SafeString(text.content)
            else:
                return SafeString(escape(text.content))
        else:
            return SafeString(
                escape(
                    "Text not found. Enter a Text with slug '{0}' and language_code '{1}'."
                    .format(slug, language_code if language_code else '')))
def load_contact(context, section, template, contact_id=None):
    _func_name = 'load_contact'
    _log_msg = f'Template Tag {_func_name}'

    request = context['request']
    page = context['page']
    language = getattr(request, 'LANGUAGE_CODE', '')

    if contact_id:
        return _load_contact_by_id(contact_id=contact_id,
                                   template=template,
                                   lang=language,
                                   log_msg=_log_msg,
                                   func_name=_func_name)
    else:
        if not section: return SafeString('')

        page_contact = page.get_contacts().first()

        if not page_contact: # pragma: no cover
            _msg = '{} cannot find contact in page {} and section {}'\
                   .format(_func_name, page, section)
            logger.error(_msg)
            return SafeString('')

        contact = page_contact.contact
        contact_infos = contact.get_infos(lang=language)
        data = {'contact': contact.localized(lang=language),
                'contact_infos': contact_infos}
        return handle_faulty_templates(template, data, name=_func_name)
Exemplo n.º 18
0
def bool_icon(value):
    if value is None:
        return "?"
    elif value:
        return SafeString("<img src='/media/admin/img/icon-yes.gif' alt='Yes' />")
    else:
        return SafeString("<img src='/media/admin/img/icon-no.gif' alt='No' />")
Exemplo n.º 19
0
def get_event_list():
    events = CalendarEvent.objects.all()
    event_list = SafeString("<ul>")
    for event in events:
        event_list += SafeString("<li>{}</li>".format(event.title))
    event_list += SafeString("</ul>")

    return event_list
Exemplo n.º 20
0
    def is_runnable(self):
        if not self.block: # pragma: no cover
            logger.warning(f'{self.iam} cannot get a block object')
            return SafeString('')
        if not getattr(self, self.collection_name, None):  # pragma: no cover
            return SafeString('')

        return self.get_placeholders()
Exemplo n.º 21
0
def manage(req, *args, **kwargs):
    binding_dates = []
    now = datetime.datetime.now().date()
    date = now
    seminars = []
    rooms = []
    durations = [
        duration.name for duration in DurationNameForSeminar.objects.all()
    ]
    while len(binding_dates) < 100:
        if date.weekday() not in [6]:
            if now.year == date.year:
                key = '%2d월 %2d일(%s)' % (date.month, date.day,
                                         name_of_weekdays[date.weekday()])
            else:
                key = '%d년 %2d월 %2d일(%s)' % (date.year, date.month, date.day,
                                             name_of_weekdays[date.weekday()])
            binding_dates.append(
                [key, '·', date.year, date.month, date.day,
                 date.weekday()])
        date += datetime.timedelta(days=1)

    for planned_seminar in PlannedSeminar.objects.all():
        seminars.append({
            'name':
            planned_seminar.title,
            'id':
            planned_seminar.id,
            'tags':
            name_of_weekdays + durations,
            'available_weekday_codes': [0, 1, 2, 3, 4],
            'available_duration_codes': [1, 3],
            'people_count':
            len(planned_seminar.post.link.recommends.all()),
            'times_of_class':
            planned_seminar.post.times_of_class
        })

    for room in RoomForSeminar.objects.all():
        rooms.append({
            'name': room.name,
            'min_people_count': room.min_people_count,
            'max_people_count': room.max_people_count
        })

    return render(
        req, 'manage.html', {
            'rooms':
            SafeString(json.dumps(rooms)),
            'binding_date':
            SafeString(json.dumps(binding_dates)),
            'seminars':
            SafeString(json.dumps(seminars)),
            'durations':
            SafeString(json.dumps(durations)),
            'all_available_tags':
            SafeString(json.dumps(name_of_weekdays + durations))
        })
Exemplo n.º 22
0
def index(request):
    context = dict()
    context[
        'auth'] = request.user.is_authenticated  # нужно для отображения меню
    context['votings'] = Voting.objects.all()
    indexes = []

    for voting in context['votings']:
        indexes.append(int(voting.id))

    context['indexes'] = indexes

    context['len'] = len(context['votings'])
    ids = dict()
    data_t = ThemeBD.objects.in_bulk()
    lent = len(data_t)

    context['theme_flag'] = (data_t[lent].Theme)
    # context['optNum'] = len(context['options'])
    la = list()
    da = list()
    for i in range(context['len']):
        context['options'] = context['votings'][i].options()
        # print(context['options'])

        labels = []
        data = []

        for option in context['options']:
            labels.append(option.text)
            data.append(option.vote_count())

        la.append(SafeString(json.dumps(labels)))
        da.append(SafeString(json.dumps(data)))

    context['la'] = la
    context['da'] = da

    if request.method == 'POST':
        single_vote(request)

    #     f = ThemeForm(request.POST)
    #     if f.is_valid():
    #         flag = bool(request.POST.get('flag'))
    #         # Сохранение данных
    #         item = ThemeBD(Theme= flag)
    #         item.save()
    #         # Формирование ответа
    #         context['flag'] = flag
    #         context['form'] = f
    #     else:
    #         context['form'] = f
    else:
        context['nothing_entered'] = True
    if request.method == 'GET':
        context['ids'] = ids
    return render(request, 'index.html', context)
Exemplo n.º 23
0
def calculateDate(notAfter):
    result = '-'
    if not isinstance(notAfter, datetime): return result
    if datetime.now(timezone.utc) > notAfter:
        result = (datetime.now(timezone.utc) - notAfter).days
        result = SafeString('<span class="light expire"></span> %s' % result)
    if notAfter > datetime.now(timezone.utc):
        result = (notAfter - datetime.now(timezone.utc)).days
        result = SafeString('<span class="light missing"></span> %s' % result)
    return result
Exemplo n.º 24
0
 def render(self, name, value, attrs=None):
     if value == {}:
         value = []
     context = {
         'name': name,
         'value': value,
         'fields': SafeString(json.dumps(self.fields)),
         'js_string': SafeString(json.dumps(value))
     }
     return mark_safe(render_to_string(self.template_name, context))
Exemplo n.º 25
0
def attr_as_p(obj, attrname):
    label = escape(attrname.capitalize())
    value = escape(getattr(obj, attrname))
    if label == 'File':
        return SafeString(f'<p><strong>{label}:</strong> <a href="/media/{value}">{value}</a></p>')
    elif label == 'Description':
        return SafeString(f'<p><strong>{label}:</strong><p><p>{value}</p>')
    elif label == 'Price':
        return SafeString(f'<p><strong>{label}:</strong> {value} PLN</p>')
    return SafeString(f'<p><strong>{label}:</strong> {value}</p>')
Exemplo n.º 26
0
def normalize_prerendered_loc_html(html: str) -> str:
    from frontend.views import DOCTYPE_HTML_TAG

    safe_html = SafeString(html)
    if safe_html.startswith(DOCTYPE_HTML_TAG):
        # This is the full HTML of the letter, return it.
        return safe_html
    # This is legacy pre-rendered HTML, so it's just the <body>; we
    # need to render the rest ourselves.
    ctx: Dict[str, Any] = {"prerendered_letter_content": safe_html}
    return render_pdf_html(None, "loc/letter-of-complaint.html", ctx, PDF_STYLES_CSS)
Exemplo n.º 27
0
def edit(request, album_id=None):
    """Shows an edit form to add new or edit an existing album."""
    context = dict(is_new=album_id is None)
    context['menu_items'] = get_menu_items('album')
    if album_id is not None:
        album = Album.objects.get(id=album_id)
        context['album'] = SafeString(json.dumps(model_to_dict(album)))
    else:
        context['album'] = SafeString(
            json.dumps(
                dict(id='', name='', year=None, best_of_compilation=False)))
    return render(request, 'albums/album/edit.html', context)
Exemplo n.º 28
0
def get_css(request):
    """Temporary: returns the css style sheet with parameters"""

    font_body = SafeString(
        'Arial, Helvetica, "Liberation Sans", FreeSans, "sans-serif"')
    font_1 = SafeString(
        'Monaco, "DejaVu Sans Mono", "Lucida Console", "Andale Mono", monospace'
    )

    content_width = '1300px'

    image = render_to_string('core/style.css', locals(), request=request)

    return HttpResponse(image, content_type="text/css")
Exemplo n.º 29
0
    def send_activation_email(self, site):
        """
        Send an activation email to the user associated with this
        ``RegistrationProfile``.

        The activation email will make use of two templates:

        ``registration/activation_email_subject.txt``
            This template will be used for the subject line of the
            email. Because it is used as the subject line of an email,
            this template's output **must** be only a single line of
            text; output longer than one line will be forcibly joined
            into only a single line.

        ``registration/activation_email.txt``
            This template will be used for the body of the email.

        These templates will each receive the following context
        variables:

        ``activation_key``
            The activation key for the new account.

        ``expiration_days``
            The number of days remaining during which the account may
            be activated.

        ``site``
            An object representing the site on which the user
            registered; depending on whether ``django.contrib.sites``
            is installed, this may be an instance of either
            ``django.contrib.sites.models.Site`` (if the sites
            application is installed) or
            ``django.contrib.sites.models.RequestSite`` (if
            not). Consult the documentation for the Django sites
            framework for etails regarding these objects' interfaces.

        """

        ctx_dict = {'activation_key': self.activation_key,
                    'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                    'site': site,
                    'user': self.user.get_username()}
        subject = render_to_string(SafeString('activation_email_subject.txt'),
                                   ctx_dict)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        message = render_to_string(SafeString('activation_email.txt'),
                                   ctx_dict)
        self.user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
Exemplo n.º 30
0
def confirm_email_change(request: HttpRequest,
                         confirmation_key: str) -> HttpResponse:
    try:
        email_change_object = get_object_from_key(confirmation_key,
                                                  [Confirmation.EMAIL_CHANGE])
    except ConfirmationKeyException as exception:
        return render_confirmation_key_error(request, exception)

    new_email = email_change_object.new_email
    old_email = email_change_object.old_email
    user_profile = email_change_object.user_profile

    if user_profile.realm.deactivated:
        return redirect_to_deactivation_notice()

    if not user_profile.is_active:
        # TODO: Make this into a user-facing error, not JSON
        raise UserDeactivatedError()

    if user_profile.realm.email_changes_disabled and not user_profile.is_realm_admin:
        raise JsonableError(
            _("Email address changes are disabled in this organization."))

    do_change_user_delivery_email(user_profile, new_email)

    context = {"realm_name": user_profile.realm.name, "new_email": new_email}
    language = user_profile.default_language
    send_email(
        "zerver/emails/notify_change_in_email",
        to_emails=[old_email],
        from_name=FromAddress.security_email_from_name(
            user_profile=user_profile),
        from_address=FromAddress.SUPPORT,
        language=language,
        context=context,
        realm=user_profile.realm,
    )

    ctx = {
        "new_email_html_tag":
        SafeString(
            f'<a href="mailto:{escape(new_email)}">{escape(new_email)}</a>'),
        "old_email_html_tag":
        SafeString(
            f'<a href="mailto:{escape(old_email)}">{escape(old_email)}</a>'),
    }
    return render(request,
                  "confirmation/confirm_email_change.html",
                  context=ctx)