Python django.conf.settings.BASE_URL Examples

The following are 30 code examples for showing how to use django.conf.settings.BASE_URL(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

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

Example 1
Project: cornerwise   Author: codeforboston   File: utils.py    License: MIT License 6 votes vote down vote up
def make_absolute_url(path, site_name=None):
    if re.match(r"^https?://", path):
        return path

    if site_name:
        config = site_config.by_hostname(site_name)
        if settings.BASE_URL:
            url_base = settings.BASE_URL
            path = add_params(path, {"_hostname": config.hostname})
        else:
            url_base = f"https://{config.hostname}"
    else:
        hostname = settings.SERVER_DOMAIN
        scheme = "http" if hostname.startswith("localhost") else "https"
        url_base = f"{scheme}://{hostname}"

    return parse.urljoin(url_base, path) 
Example 2
Project: astrobin   Author: astrobin   File: group_reject_join_request.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        if request.is_ajax():
            group = self.get_object()
            user = UserProfile.objects.get(user__pk=self.request.POST.get('user')).user

            if user not in group.join_requests.all():
                return HttpResponseForbidden()

            group.join_requests.remove(user)
            push_notification([user], 'group_join_request_rejected',
                              {
                                  'group_name': group.name,
                                  'url': settings.BASE_URL + reverse('group_detail', args=(group.pk,)),
                              })

            return self.render_json_response({
                'member': user.pk,
            })

        # Only AJAX allowed
        return HttpResponseForbidden() 
Example 3
Project: astrobin   Author: astrobin   File: signals.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def imagerevision_post_save(sender, instance, created, **kwargs):
    if created and not instance.image.is_wip and not instance.skip_notifications:
        followers = [x.user for x in ToggleProperty.objects.filter(
            property_type="follow",
            content_type=ContentType.objects.get_for_model(User),
            object_id=instance.image.user.pk)]

        push_notification(followers, 'new_image_revision',
                          {
                              'object_url': settings.BASE_URL + instance.get_absolute_url(),
                              'originator': instance.image.user.userprofile.get_display_name(),
                          })

        add_story(instance.image.user,
                  verb='VERB_UPLOADED_REVISION',
                  action_object=instance,
                  target=instance.image) 
Example 4
Project: astrobin   Author: astrobin   File: signals.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def solution_post_save(sender, instance, created, **kwargs):
    ct = instance.content_type

    try:
        target = ct.get_object_for_this_type(pk=instance.object_id)
    except ct.model_class().DoesNotExist:
        return

    if ct.model == 'image':
        user = target.user
    elif ct.model == 'imagerevision':
        user = target.image.user
    else:
        return

    if instance.status == Solver.FAILED:
        notification = 'image_not_solved'
    elif instance.status == Solver.SUCCESS:
        notification = 'image_solved'
    else:
        return

    push_notification([user], notification,
                      {'object_url': settings.BASE_URL + target.get_absolute_url()}) 
Example 5
Project: astrobin   Author: astrobin   File: signals.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def forum_topic_pre_save(sender, instance, **kwargs):
    if not hasattr(instance.forum, 'group'):
        return

    try:
        topic = sender.objects.get(pk=instance.pk)
    except sender.DoesNotExist:
        pass
    else:
        if topic.on_moderation == True and instance.on_moderation == False:
            # This topic is being approved
            group = instance.forum.group
            push_notification(
                [x for x in group.members.all() if x != instance.user],
                'new_topic_in_group',
                {
                    'user': instance.user.userprofile.get_display_name(),
                    'url': settings.BASE_URL + instance.get_absolute_url(),
                    'group_url': reverse_url('group_detail', kwargs={'pk': group.pk}),
                    'group_name': group.name,
                    'topic_title': instance.name,
                },
            ) 
Example 6
Project: astrobin   Author: astrobin   File: signals.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def forum_topic_post_save(sender, instance, created, **kwargs):
    if created and hasattr(instance.forum, 'group'):
        group = instance.forum.group

        if instance.on_moderation:
            recipients = group.moderators.all()
        else:
            recipients = group.members.all()
        recipients = [x for x in recipients if x != instance.user]

        push_notification(
            recipients,
            'new_topic_in_group',
            {
                'user': instance.user.userprofile.get_display_name(),
                'url': settings.BASE_URL + instance.get_absolute_url(),
                'group_url': settings.BASE_URL + reverse_url('group_detail', kwargs={'pk': group.pk}),
                'group_name': group.name,
                'topic_title': instance.name,
            },
        ) 
Example 7
Project: astrobin   Author: astrobin   File: models.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def approve(self):
        app, created = App.objects.get_or_create(
            registrar=self.registrar, name=self.name,
            description=self.description)

        self.approved = True
        self.save()

        if created:
            push_notification(
                [self.registrar], 'api_key_request_approved',
                {'api_docs_url': settings.BASE_URL + '/help/api/',
                 'api_keys_url': settings.BASE_URL + '/users/%s/apikeys/' % self.registrar.username,
                 'key': app.key,
                 'secret': app.secret})
        else:
            app.active = True

        app.save() 
Example 8
Project: acacia_main   Author: AcaciaTrading   File: models.py    License: MIT License 5 votes vote down vote up
def send_email(self, email_type):
        from django.core.mail import send_mail
        from django.template.loader import render_to_string
        from django.conf import settings
        
        email_content = render_to_string(
            "billing/invoice_%s.txt" % email_type,
            context={
                "username":self.customer.user.username,
                "amount":self.amount_string(),
                "due_date":datetime.datetime.fromtimestamp(
                    self.customer.expiry_timestamp
                ).strftime('%B %-d'),
                "invoice_id":self.pk,
                "base_url":settings.BASE_URL
            }
        )
        
        result = send_mail(
            'Your Acacia Invoice',
            email_content,
            'noreply@tradeacacia.com',
            [self.customer.user.email],
            fail_silently=True
        )
        return result == 1 
Example 9
Project: freesound-datasets   Author: MTG   File: utils.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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) 
Example 10
Project: openduty   Author: ustream   File: helper.py    License: MIT License 5 votes vote down vote up
def generate_notifications_for_incident(incident):
        now = timezone.make_aware(datetime.now(), timezone.get_current_timezone())
        duty_officers = get_escalation_for_service(incident.service_key)

        current_time = now

        notifications = []

        for officer_index, duty_officer in enumerate(duty_officers):
            escalation_time = incident.service_key.escalate_after * (officer_index + 1)
            escalate_at = current_time + timedelta(minutes=escalation_time)

            methods = duty_officer.notification_methods.order_by('position').all()
            method_index = 0

            for method in methods:
                notification_time = incident.service_key.retry * method_index + incident.service_key.escalate_after * officer_index
                notify_at = current_time + timedelta(minutes=notification_time)
                if notify_at < escalate_at:
                    notification = ScheduledNotification()
                    notification.incident = incident
                    notification.user_to_notify = duty_officer
                    notification.notifier = method.method
                    notification.send_at = notify_at
                    uri = settings.BASE_URL + "/incidents/details/" + str(incident.id)
                    notification.message = "A Service is experiencing a problem: " + incident.incident_key + " " + incident.description + ". Handle at: " + uri + " Details: " + incident.details

                    notifications.append(notification)

                    print "Notify %s at %s with method: %s" % (duty_officer.username, notify_at, notification.notifier)
                else:
                    break
                method_index += 1

            # todo: error handling

        return notifications 
Example 11
Project: openduty   Author: ustream   File: helper.py    License: MIT License 5 votes vote down vote up
def generate_notifications_for_user(incident, user, delay=None, preparedmsg = None):

        now = timezone.make_aware(datetime.now(), timezone.get_current_timezone())
        current_time = now
        notifications = []
        methods = user.notification_methods.order_by('position').all()
        method_index = 0

        for method in methods:
            if delay is None:
                notification_time = incident.service_key.retry * method_index + incident.service_key.escalate_after
            else:
                notification_time = method_index * delay
            notify_at = current_time + timedelta(minutes=notification_time)
            notification = ScheduledNotification()
            notification.incident = incident
            notification.user_to_notify = user
            notification.notifier = method.method
            notification.send_at = notify_at
            if preparedmsg is None:
                uri = settings.BASE_URL + "/incidents/details/" + str(incident.id)
                notification.message = "A Service is experiencing a problem: " + incident.incident_key + " " + incident.description + ". Handle at: " + uri
            else:
                notification.message = preparedmsg
            notifications.append(notification)
            print "Notify %s at %s with method: %s" % (user.username, notify_at, notification.notifier)
            method_index += 1

        # todo: error handling
        return notifications 
Example 12
Project: mrs   Author: betagouv   File: models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def daily_mail(force=False):
    if date.today() in holidays.France() and not force:
        return

    for caisse in Caisse.objects.filter(active=True):
        mrsrequests = caisse.mrsrequest_set.all().status('new').order_by(
            'creation_datetime')

        if not len(mrsrequests):
            continue

        context = dict(
            object_list=mrsrequests,
            BASE_URL=settings.BASE_URL,
            ADMIN_ROOT=crudlfap.site.views['home'].url,
        )

        Caller(
            callback='djcall.django.email_send',
            kwargs=dict(
                subject=template.loader.get_template(
                    'caisse/liquidation_daily_mail_title.txt',
                ).render(context).strip(),
                body=template.loader.get_template(
                    'caisse/liquidation_daily_mail_body.html',
                ).render(context).strip(),
                to=[caisse.liquidation_email],
                reply_to=[settings.DEFAULT_FROM_EMAIL],
                content_subtype='html'
            )
        ).spool('mail') 
Example 13
Project: mrs   Author: betagouv   File: models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def password_reset(self, caisse):
        created = not self.password
        password = secrets.token_urlsafe(16)
        self.set_password(password)
        self.save()
        password_email_template = template.loader.get_template(
            'mrsuser/user_password_email.txt',
        )
        # In case of super admins not linked to any caisse, reply_to heads
        # to settings.TEAM_EMAIL
        email = caisse.habilitation_email if caisse else None

        if email:
            reply_to = email
        else:
            reply_to = settings.TEAM_EMAIL
        Caller(
            callback='djcall.django.email_send',
            kwargs=dict(
                subject=(
                    '[MRS] Votre mot de passe'
                    if created else
                    '[MRS] Votre nouveau mot de passe'
                ),
                body=password_email_template.render(dict(
                    created=created,
                    user=self,
                    password=password,
                    BASE_URL=settings.BASE_URL,
                )),
                to=[self.email],
                reply_to=[reply_to],
            )
        ).spool('mail') 
Example 14
Project: mrs   Author: betagouv   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        if self.object.status != self.object.STATUS_NEW:
            return http.HttpResponseBadRequest()

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

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

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

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

        return generic.TemplateView.get(self, request, *args, **kwargs) 
Example 15
Project: instiapp-api   Author: wncc   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, obj, index):
        has_canonical = hasattr(obj, 'canonical_name') and obj.canonical_name
        self.name = obj.canonical_name if has_canonical else obj.name
        self.url = settings.BASE_URL + url_mapping[obj.__class__] + obj.str_id
        self.index = index 
Example 16
Project: wagtail-torchbox   Author: torchbox   File: feeds.py    License: MIT License 5 votes vote down vote up
def item_enclosure_url(self, item):
        if item.feed_image:
            return settings.BASE_URL + item.feed_image.file.url 
Example 17
Project: teamvault   Author: seibert-media   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super(OpenSearch, self).get_context_data(**kwargs)
        context['base_url'] = settings.BASE_URL
        return context 
Example 18
Project: teamvault   Author: seibert-media   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def assign_reviewers(self):
        candidates = list(self.secret.notify_on_access_request.filter(is_active=True))
        if len(candidates) < 3:
            candidates += list(
                self.secret.allowed_users.order_by('-last_login').filter(is_active=True)[:10]
            )
            for group in self.secret.allowed_groups.all():
                candidates += list(group.user_set.order_by('-last_login').filter(is_active=True)[:3])
        if len(candidates) < 3:
            candidates += list(User.objects.filter(
                is_active=True,
                is_superuser=True,
            ).order_by('-last_login')[:3])
        candidates = set(candidates)
        selected = sample(candidates, min(3, len(candidates)))
        if not selected:
            raise RuntimeError(_("unable to find reviewers for {}").format(self))
        self.reviewers.set(selected)

        send_mail(
            self.reviewers.all(),
            _("[TeamVault] Review access request for '{}'").format(self.secret.name),
            "secrets/mail_access_request_review",
            context={
                'access_request_url': reverse(
                    'secrets.access_request-detail',
                    kwargs={'hashid': self.hashid},
                ),
                'base_url': settings.BASE_URL,
                'secret_name': self.secret.name,
                'secret_url': self.secret.get_absolute_url(),
                'username': self.requester.username,
            },
            user_from=self.requester,
        ) 
Example 19
Project: teamvault   Author: seibert-media   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def full_url(self):
        return settings.BASE_URL.rstrip("/") + self.get_absolute_url() 
Example 20
Project: wagtail-review   Author: wagtail   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_review_url_impl(token):
    return settings.BASE_URL + reverse('wagtail_review:review', args=[token.encode()]) 
Example 21
Project: freedomvote   Author: freedomvote   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def party_logout_view(request, party_name):
    logout(request)

    return redirect(settings.BASE_URL) 
Example 22
Project: freedomvote   Author: freedomvote   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def unique_url(self):
        return '%s%s' % (
            settings.BASE_URL,
            reverse('politician_edit', args=[self.unique_key])
        ) 
Example 23
Project: freedomvote   Author: freedomvote   File: admin.py    License: GNU General Public License v3.0 5 votes vote down vote up
def unique_url(self, obj):
        return '%s%s' % (
            settings.BASE_URL,
            reverse('politician_edit_profile', args=(obj.unique_key,))
        ) 
Example 24
Project: astrobin   Author: astrobin   File: iotd.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def item_link(self, item):
        return settings.BASE_URL + reverse('image_detail', kwargs={
            'id': item.image.get_id()
        }) 
Example 25
Project: astrobin   Author: astrobin   File: iotd.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def item_author_link(self, item):
        return settings.BASE_URL + reverse('user_page', args=(item.image.user.username,)) 
Example 26
Project: astrobin   Author: astrobin   File: top_picks.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def item_link(self, item):
        return settings.BASE_URL + reverse('image_detail', kwargs={
            'id': item.get_id()
        }) 
Example 27
Project: astrobin   Author: astrobin   File: top_picks.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def item_author_link(self, item):
        return settings.BASE_URL + reverse('user_page', args=(item.user.username,)) 
Example 28
Project: astrobin   Author: astrobin   File: group_invite.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        group = self.get_object()
        for pk in request.POST.getlist('users[]'):
            try:
                user = UserProfile.objects.get(user__pk=pk).user
            except UserProfile.DoesNotExist:
                continue

            group.invited_users.add(user)
            push_notification([user], 'new_group_invitation',
                              {
                                  'inviter': request.user.userprofile.get_display_name(),
                                  'inviter_page': reverse('user_page', args=(request.user.username,)),
                                  'group_name': group.name,
                                  'group_page': settings.BASE_URL + reverse('group_detail', args=(group.pk,)),
                              })

        if request.is_ajax():
            return self.render_json_response({
                'invited_users': [{
                    'id': x.id,
                    'username': x.username,
                    'display_name': x.userprofile.get_display_name(),
                    'url': reverse('user_page', args=(x.username,)),
                    'revoke_url': reverse('group_revoke_invitation', args=(group.pk,)),
                } for x in group.invited_users.all()]
            })

        return redirect(self.get_success_url()) 
Example 29
Project: astrobin   Author: astrobin   File: group_join.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        group = self.get_object()

        def doAdd(user, group):
            group.members.add(user)
            group.invited_users.remove(user)
            group.join_requests.remove(user)
            messages.success(request, _("You have joined the group"))

        if request.user in group.members.all():
            messages.error(request, _("You already were a member of this group"))
            return redirect(self.get_success_url())

        if group.public:
            if group.moderated and request.user != group.owner:
                group.join_requests.add(request.user)
                messages.warning(request,
                                 _("This is a moderated group, and your join request will be reviewed by a moderator"))
                push_notification(group.moderators.all(), 'new_group_join_request',
                                  {
                                      'requester': request.user.userprofile.get_display_name(),
                                      'group_name': group.name,
                                      'url': settings.BASE_URL + reverse('group_moderate_join_requests',
                                                                         args=(group.pk,)),
                                  })
                return redirect(self.get_success_url())
            else:
                doAdd(request.user, group)
                return redirect(self.get_success_url())
        else:
            if request.user in group.invited_users.all() or request.user == group.owner:
                doAdd(request.user, group)
                return redirect(self.get_success_url())

        return HttpResponseForbidden() 
Example 30
def handle(self, *args, **kwargs):
        # To avoid sending too many emails, only get the users that joined on the same day of the month as today. By
        # running this script daily, you get to spread all these emails over a period of 30 days, and each user doesn't
        # get it more often than once a month.
        for user in User.objects.filter(date_joined__day = date.today().day):
            images = Image.objects.filter(user=user, data_source="UNSET")

            if images.count() > 0:
                push_notification([user], 'missing_data_source', {
                    'BASE_URL': settings.BASE_URL,
                    'images': images
                })