Python django.conf.settings 模块,BASE_URL 实例源码

我们从Python开源项目中,提取了以下28个代码示例,用于说明如何使用django.conf.settings.BASE_URL

项目:Quantrade    作者:quant-trade    | 项目源码 | 文件源码
def password(request):
    previous_page = settings.BASE_URL

    if request.user.has_usable_password():
        PasswordForm = PasswordChangeForm
    else:
        PasswordForm = AdminPasswordChangeForm

    if request.method == 'POST':
        form = PasswordForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            messages.success(request, 'Your password was successfully updated!')
            #return redirect('password')
            return render(request, 'registration/password_thanks.html', {'form': form, 'previous_page': previous_page } )
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordForm(request.user)

    return render(request, 'registration/password.html', {'form': form } )
项目:covart-web    作者:cyliang    | 项目源码 | 文件源码
def form_valid(self, form):
        if form.cleaned_data['email_notification']:
            # Send notification if the presenter desire.
            data = {
                'presentation': self.object,
                'base_url': settings.BASE_URL,
            }

            if self.object.present_type == self.model.PAPER_PRESENTATION:
                data['paper'] = website_models.Publication.get_from_keyword(self.object.content)

            text_body = render_to_string('meeting/update_content_email.txt', data)
            html_body = render_to_string('meeting/update_content_email.html', data)

            async('meeting.tasks.send_notification',
                meeting=self.object.meeting,
                body=text_body,
                html_body=html_body,
            )

        return super(PresentUpdateView, self).form_valid(form)
项目:covart-web    作者:cyliang    | 项目源码 | 文件源码
def form_valid(self, form):
        if form.cleaned_data['email_notification']:
            # Send notification if desired.
            data = {
                'attendance': self.object,
                'base_url': settings.BASE_URL,
            }

            text_body = render_to_string('meeting/take_leave_email.txt', data)
            html_body = render_to_string('meeting/take_leave_email.html', data)

            async('meeting.tasks.send_notification',
                meeting=self.object.meeting,
                body=text_body,
                html_body=html_body,
            )

        if date.today() < self.object.meeting.date:
            self.object.status = models.MeetingAttendance.LEAVE_BEFORE
        elif self.object.status != models.MeetingAttendance.LEAVE_BEFORE:
            self.object.status = models.MeetingAttendance.LEAVE_AFTER

        return super(TakeLeaveView, self).form_valid(form)
项目:moore    作者:UTNkar    | 项目源码 | 文件源码
def send_confirmation_email(sender, email, user=None, **kwargs):
    user = user or sender  # TODO: use user.send_email
    if user is not None:
        context = {
            'email': email,
            'domain': settings.BASE_URL,
            'site_name': settings.WAGTAIL_SITE_NAME,
            'token': user.get_confirmation_key(email),
            'new_user': user.get_confirmed_emails() == []
        }

        subject = loader.render_to_string(
            'members/email_change_subject.txt', context)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = loader.render_to_string('members/email_change_email.html',
                                       context)

        email_message = EmailMultiAlternatives(subject, body, None, [email])
        email_message.send()
项目:uwcs-zarya    作者:davidjrichardson    | 项目源码 | 文件源码
def make_user_site_config(username):
    # Render the config file
    config = render_to_string('accounts/members_template.conf', {
        'user': username,
        'ssl_cipher_suite': settings.APACHE_SSL_CIPHER_SUITE,
        'ssl_cert': settings.APACHE_SSL_CERT_FILE,
        'ssl_key': settings.APACHE_SSL_KEY_FILE,
        'ssl_chain': settings.APACHE_SSL_CHAIN_FILE,
        'website_dir': settings.APACHE_WEBSITE_DIR,
        'base_url': settings.BASE_URL
    })

    # Save it to a file on the filesystem
    config_file = open(
        '{sites_available}/members-{nickname}.conf'.format(sites_available=settings.APACHE_SITES_AVAILABLE,
                                                           nickname=username), 'w')
    config_file.write(config)
    config_file.close()

    # Symlink the config files to enable the site and restart apache
    os.symlink('{sites_available}/members-{nickname}.conf'.format(sites_available=settings.APACHE_SITES_AVAILABLE,
                                                                  nickname=username),
               '{sites_enabled}/members-{nickname}.conf'.format(sites_enabled=settings.APACHE_SITES_ENABLED,
                                                                nickname=username))
    subprocess.call(['service', 'apache2', 'reload'], shell=False)
项目:opencon-2016-app-code    作者:sparcopen    | 项目源码 | 文件源码
def invite(self):
        """
        Send invite mail to application email address.
        """
        if not settings.REVIEWER_MAIL_ENABLED:
            return

        context = {
            "user": self,
            "link": "{}{}".format(
                settings.BASE_URL,
                reverse("rating:rate", args=[self.uuid])
            )
        }

        subject = render_to_string(
            "rating/email/invite.subject", context
        ).strip()
        message = render_to_string("rating/email/invite.message", context)

        send_mail(
            subject,
            message,
            settings.FROM_MAIL,
            [self.email],
            fail_silently=False
        )
        self.invitation_sent = True
        self.save()
项目:Quantrade    作者:quant-trade    | 项目源码 | 文件源码
def extra_context(request):
    try:
        user = request.user
    except:
        user = None

    return {'base_url': settings.BASE_URL[:-1],
            'sitename': site_name,
            'user': user,
            'members_area_nae': 'members',
            'broker_base': broker_base,
            'dev': settings.DEV_ENV,
            'version': settings.VERSION,
            'noncustomerlimit': settings.LIMIT_STRATEGIES_FOR_NON_CUSTOMERS }
项目:QProb    作者:quant-trade    | 项目源码 | 文件源码
def item_link(self, item):
        return "{0}{1}/".format(settings.BASE_URL, item.slug)
项目:QProb    作者:quant-trade    | 项目源码 | 文件源码
def extra_context(request):
    cats = Category.objects.all()

    c = []
    for cat in cats:
        cats_ = {}
        cats_['cnt'] = Post.objects.filter(category=cat.title).count()
        cats_['title'] = cat.title
        cats_['slug'] = cat.slug
        if cats_['cnt'] > 0:
            c.append(cats_)

    archive = []
    years = Post.objects.dates('date', 'year')
    for year in years:
        archive.append({'year': year.year, 'cnt': Post.objects.filter(date__year=year.year).count()})

    return {'base_url': settings.BASE_URL[:-1],
            'sitename': settings.SITE_NAME,
            'cats': c,
            'keyword': settings.KEYWORD,
            'shot_site_name': settings.SHORT_SITE_NAME,
            'research_module': settings.RESEARCH_MODULE,
            'definitions_module': settings.DEFINITIONS_MODULE,
            'twitter_handle': settings.TWITTER_HANDLE,
            'facebook_handle': settings.FACEBOOK_HANDLE,
            'linkedin_handle': settings.LINKEDIN_HANDLE,
            'gplus_handle': settings.GOOGLE_PLUS_HANDLE,
            'logo_handle': settings.LOGO_HANDLE,
            'feedburner_uri': settings.FEEDBURNER_URI,
            'copyright': settings.COPYRIGHT,
            'search_title': settings.SEARCH_TITLE,
            'site_theme': settings.SITE_THEME,
            'first_page_title': settings.FIRST_PAGE_TITLE,
            'advert': settings.AD_CODE,
            'host': settings.HOST,
            'folder': settings.SITE_FOLDER,
            'years': archive,
            'mobile_app_url': settings.MOBILE_APP_URL,
            'app_name': 'aggregator' }
项目:covart-web    作者:cyliang    | 项目源码 | 文件源码
def rollcall_notification():
    """
    This task send a rollcall notification to each presenter.
    """
    from django.template.loader import render_to_string

    try:
        meeting = models.MeetingHistory.objects.get(date=date.today())
    except models.MeetingHistory.DoesNotExist:
        return 'There is no meeting today. Aborted.'

    data = {
        'meeting': meeting,
        'base_url': settings.BASE_URL,
    }

    text_body = render_to_string('meeting/rollcall_email.txt', data)
    html_body = render_to_string('meeting/rollcall_email.html', data)

    def get_email(member):
        return member.get_internal_email()

    send_notification(
        subject=meeting.date.strftime('Rollcall Notification (%m/%d)'),
        recipients=filter(lambda e: e != None, map(get_email, meeting.presenters.all())),
        body=text_body,
        html_body=html_body,
    )
项目:covart-web    作者:cyliang    | 项目源码 | 文件源码
def _url(url):
    return settings.BASE_URL + url
项目:freesound-datasets    作者:MTG    | 项目源码 | 文件源码
def generate_download_script(dataset):
    access_token_url = urljoin(settings.BASE_URL, reverse('get_access_token'))
    dataset_url = urljoin(settings.BASE_URL, reverse('dataset-sounds',
        kwargs={"short_name": dataset.short_name}))

    tvars = {
        'access_token_url': access_token_url,
        'dataset_url': dataset_url,
        'get_code_url': settings.FS_CLIENT_ID
    }
    return render_to_string('datasets/download_script.py', tvars)
项目:ac-mediator    作者:AudioCommons    | 项目源码 | 文件源码
def collect_response(self, response_id):
        response = self.store.get_response(response_id)
        if response is None:
            return None
        to_return = response.copy()
        to_return['meta']['response_id'] = response_id  # Add response_id to returned dictionary
        to_return['meta']['collect_url'] = settings.BASE_URL + '{0}?rid={1}'.format(reverse('api-collect'), response_id)  # Add collect url for convinience
        to_return['meta']['current_timestamp'] = str(datetime.datetime.now())
        if response['meta']['status'] == RESPONSE_STATUS_FINISHED and settings.DELETE_RESPONSES_AFTER_CONSUMED:
            self.store.delete_response(response_id)  # If response has been all loaded, delete it from pool
        return to_return
项目:ac-mediator    作者:AudioCommons    | 项目源码 | 文件源码
def render(self, context):
        path = super(AbsoluteURLNode, self).render(context)
        domain = settings.BASE_URL
        return urljoin(domain, path)
项目:ac-mediator    作者:AudioCommons    | 项目源码 | 文件源码
def get_redirect_uri(self):
        return settings.BASE_URL + reverse('link_service_callback', args=[self.id])
项目:moore    作者:UTNkar    | 项目源码 | 文件源码
def send_extension_emails():
    vacant_positions = Position.objects.filter(
        recruitment_end=date.today() - timedelta(days=1),
    ).exclude(
        applications__status='submitted'
    )

    for pos in vacant_positions:
        context = {
            'email': pos.role.election_email,
            'domain': settings.BASE_URL,
            'position': pos,
        }
        subject = loader.render_to_string(
            'involvement/admin/extend_deadline_subject.txt', context
        )
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = loader.render_to_string(
            'involvement/admin/email_extend_deadline.html', context
        )

        email_message = EmailMultiAlternatives(
            subject, body, None, [pos.role.election_email]
        )
        email_message.send()
项目:cyphon    作者:dunbarcyber    | 项目源码 | 文件源码
def get_attachment_url(path):
    """

    """
    base_url = urllib.parse.urljoin(settings.BASE_URL, settings.MEDIA_URL)
    return urllib.parse.urljoin(base_url, path)
项目:cyphon    作者:dunbarcyber    | 项目源码 | 文件源码
def link(self):
        """

        """
        base_url = settings.BASE_URL
        return urllib.parse.urljoin(base_url, _ALERT_URL + str(self.id))
项目:a4-meinberlin    作者:liqd    | 项目源码 | 文件源码
def replace_relative_media_urls(text):
        if not settings.MEDIA_URL.startswith('/'):
            # Replace only if MEDIA_URL is relative
            return text

        # Find every occurrence of the MEDIA_URL that is either following a
        # whitespace, an equal sign or a quotation mark.
        pattern = re.compile(r'([\s="\'])(%s)' % re.escape(settings.MEDIA_URL))
        text = re.sub(pattern, r'\1%s\2' % settings.BASE_URL, text)
        return text
项目:a4-meinberlin    作者:liqd    | 项目源码 | 文件源码
def test_absolute_media_urls(newsletter_factory):
    base = 'Relative {rel}test.png' \
           'Tag1: href={rel}test.png' \
           'Tag2: href="{rel}test.png"' \
           "Tag3: href='{rel}test.png'" \
           'Absolute: http://foo.bar/{abs}test.png'

    body = base.format(rel=settings.MEDIA_URL,
                       abs=settings.MEDIA_URL)
    newsletter = newsletter_factory(body=body)

    expected = base.format(rel=settings.BASE_URL + settings.MEDIA_URL,
                           abs=settings.MEDIA_URL)
    assert body == newsletter.body
    assert expected == newsletter.body_with_absolute_urls
项目:oim-cms    作者:parksandwildlife    | 项目源码 | 文件源码
def get_url(self, obj):
        return '{0}/catalogue/api/records/{1}.json'.format(settings.BASE_URL, obj.identifier)
项目:oim-cms    作者:parksandwildlife    | 项目源码 | 文件源码
def metadata_link(self ):
        return {
            'endpoint': '{0}/catalogue/'.format(settings.BASE_URL), 
            'version': '2.0.2', 
            'type': 'CSW', 
            'link':'{0}/catalogue/?version=2.0.2&service=CSW&request=GetRecordById&elementSetName=full&typenames=csw:Record&resultType=results&id={1}'.format(settings.BASE_URL, self.identifier)
        }
项目:oim-cms    作者:parksandwildlife    | 项目源码 | 文件源码
def generate_style_link(style):
        #schema =  '{{"protocol":"application/{0}", "name":"{1}", "default":"{2}", "linkage":"{3}/media/"}}'.format(style.format.lower(), style.name, style.default, settings.BASE_URL)
        schema = {
            "protocol" : "application/{}".format(style.format.lower()), 
            "name": style.name, 
            "default": style.default, 
            "linkage":"{}/media/a".format(settings.BASE_URL)
        }
        return 'None\tNone\t{0}\t{1}/media/{2}'.format(json.dumps(schema), settings.BASE_URL, style.content)
项目:devolio    作者:devolio    | 项目源码 | 文件源码
def slack_question_msg(question):
    return {
        "title": question.title,
        "author_name": "@{}".format(question.user.username),
        "author_link": "{}/@{}".format(settings.BASE_URL, question.user.username),
        "color": "#f78250",
        "title_link": "{}{}".format(settings.BASE_URL, question.get_absolute_url()),
        "pretext": "Ok, I published your question on Devolio!",
        "footer": "devolio.net",
        }
项目:devolio    作者:devolio    | 项目源码 | 文件源码
def full_url(path):
    return "{}{}".format(settings.BASE_URL, path)
项目:devolio    作者:devolio    | 项目源码 | 文件源码
def slack_msg(instance):
    return {
        "title": instance.title,
        "author_name": "@{}".format(instance.user.username),
        "author_link": "{}/@{}".format(settings.BASE_URL, instance.user.username),
        "color": "#f78250",
        "title_link": full_url(instance.get_absolute_url()),
        "pretext": "New question!",
        "footer": "devolio.net",
        }
项目:fire    作者:FundersClub    | 项目源码 | 文件源码
def msg_to_markdown(repo, msg):
    def absurl(url):
        if not url.startswith('http:/') and not url.startswith('https:'):
            slash = '' if settings.BASE_URL.endswith('/') or url.startswith('/') else '/'
            return settings.BASE_URL + slash + url
        return url

    # Need a map of content id -> attachment
    all_attachments = list(msg.attachment_set.all())
    attachments_map = {}
    for att in all_attachments:
        if att.content_id:
            attachments_map[att.content_id] = att

    # Attempt to update img elements pointing to an attach,ment
    attachments_observed = set()
    if msg.body_html:
        soup = BeautifulSoup(msg.body_html, 'html.parser')
        for img in soup.find_all('img'):
            src = img.attrs.get('src')
            if not src or not src.startswith('cid:'):
                continue

            att = attachments_map.get(src.replace('cid:', ''))
            if att:
                img['src'] = att.file.url
                attachments_observed.add(att)

        h = html2text.HTML2Text(bodywidth=0)
        msg_body = h.handle(str(soup))
    else:
        msg_body = msg.body_text

    # Look for attachments we didn't display inline
    attachments = list(att for att in all_attachments if att not in attachments_observed)
    if attachments:
        attachments_text = u'\n\n\n\n---\n*Attachments:*\n\n'
        for att in attachments:
            url = att.file.url
            filename = os.path.basename(att.file.name)
            inline_img = ''
            if filename.lower().split('.')[-1] in ('png', 'gif', 'jpeg', 'jpg' 'svg'):
                inline_img = u'\n  ![]({})\n'.format(url)
            attachments_text += u'1. [{}]({}){}\n'.format(filename, url, inline_img)
    else:
        attachments_text = ''

    # See if we recognize this email address
    map_entry = repo.emailmap_set.filter(email__iexact=msg.from_email).first()
    if map_entry:
        tag = '@' + map_entry.login
    else:
        tag = msg.from_name

    return u'*Sent by {} ({}). Created by [fire]({}/).*\n\n---\n{}{}'.format(
        tag,
        msg.from_email,
        settings.BASE_URL,
        msg_body,
        attachments_text,
    )
项目:covart-web    作者:cyliang    | 项目源码 | 文件源码
def meeting_notification():
    from django.template.loader import render_to_string

    next_meeting = models.MeetingHistory.objects.all()[:1][0]

    data = {
        'meeting': next_meeting,
        'base_url': settings.BASE_URL,
    }

    if next_meeting.date - date.today() > timedelta(days=7):
        # The meeting is postponed.
        postponed_date = models.MeetingHistory.get_next_meeting_date()

        reason = ''
        skip = list(models.MeetingSkip.objects.filter(date=postponed_date))
        if len(skip) > 0 and skip[0].reason != '':
            reason = ' because of %s' % skip[0].reason

        data['postponed_date'] = postponed_date
        data['reason'] = reason

        # Notify with Slack
        async(send_slack_postponed_meeting, next_meeting, postponed_date, reason)

        template_name = 'meeting/postpone_email'
        subject = postponed_date.strftime('Group Meeting Postponed (%m/%d)')
        ret = 'Meeting postponing message sent'
    else:
        # Notify with Slack
        async(sync_meeting_with_slack, next_meeting)

        template_name = 'meeting/notify_email'
        subject = next_meeting.get_email_title()
        ret = 'Meeting notification for %s sent.' % unicode(next_meeting)

    text_body = render_to_string(template_name + '.txt', data)
    html_body = render_to_string(template_name + '.html', data)

    send_notification(
        subject=subject,
        body=text_body,
        html_body=html_body,
    )

    return ret