Python django.conf.settings.SITE_URL Examples

The following are 15 code examples of django.conf.settings.SITE_URL(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: app_serializers.py    From cmdb with GNU Lesser General Public License v3.0 6 votes vote down vote up
def create(self, validated_data):
        password = get_random_string(10)
        user = User.objects.create_user(**validated_data)
        # user = super().create(**validated_data)
        user.set_password(password)
        user.save()
        username = validated_data["username"]
        permissions = "管理员" if validated_data["is_staff"] else "普通用户"
        try:
            send_mail("CMDB 用户创建成功",
                      "Hi, {}, 您的CMDB用户已成功创建:\n\t用户名:{}\n\t权限:{}\n\t初始密码:{}\n\t网站地址:{}".format(
                          username, username, permissions, password, settings.SITE_URL),
                      settings.SEND_EMAIL,
                      [validated_data["email"]],
                      fail_silently=False)
        except Exception as exc:
            logger.error(f"用户创建成功 邮件发送失败 {exc}")
            raise exceptions.ParseError("用户创建成功 邮件发送失败")
        return user

    # def update(self, instance, validated_data):
    #     super().update(instance, validated_data)
    #     if "password" in validated_data:
    #         instance.set_password(validated_data)
    #     return instance 
Example #2
Source File: views.py    From shortweb with MIT License 6 votes vote down vote up
def is_already_short(url):
    popular_shortening_urls = [
        'bit.ly/',
        'goo.gl/',
        'ow.ly/',
        'is.gd/',
        'buff.ly/',
        'adf.ly/',
        'tinyurl.com/',
        'bit.do/',
        'mcaf.ee/',
        't.co/',
        'tiny.cc/',
        'shorte.st/',
        'idek.net/',
        'po.st/',
        'yep.it/',
        'tr.im/',
        settings.SITE_URL,
    ]
    for shortening_url in popular_shortening_urls:
        if shortening_url in url:
            return True
    return False 
Example #3
Source File: templatetags.py    From telemetry-analysis-service with Mozilla Public License 2.0 5 votes vote down vote up
def full_url(url):
    """
    A Django template filter to prepend the given URL path with the full
    site URL.
    """
    return urljoin(settings.SITE_URL, url) 
Example #4
Source File: 0001_initial_site.py    From telemetry-analysis-service with Mozilla Public License 2.0 5 votes vote down vote up
def add_site(apps, schema_editor):
    Site = apps.get_model("sites", "Site")
    db_alias = schema_editor.connection.alias
    domain = urlparse(settings.SITE_URL)
    Site.objects.using(db_alias).get_or_create(
        id=settings.SITE_ID, defaults={"domain": domain.netloc, "name": domain.netloc}
    ) 
Example #5
Source File: tasks.py    From opensurfaces with MIT License 5 votes vote down vote up
def prefetch_page_task(base_url=None, maxdepth=2):
    """ Prefetch pages, breadth-first, to populate the cache.  """
    if not settings.ENABLE_CACHING:
        logger.info("Caching disabled -- not prefetching")
        return
    if not base_url:
        base_url = settings.SITE_URL
    if not base_url.endswith('/'):
        base_url += '/'

    to_visit = deque()
    to_visit.append((base_url, 0))
    visited = set()
    while len(to_visit) > 0:
        url, depth = to_visit.popleft()
        visited.add(url)
        if not url.startswith(base_url):
            continue
        try:
            start = time()
            text = urllib2.urlopen(url).read()
            elapsed = time() - start
            logger.info('prefetch (%s, %.3f s): %s' % (depth, elapsed, url))
        except Exception as exc:
            logger.error(
                'prefetch (%s): error fetching %s: %s' % (depth, url, exc))
            return
        if depth < maxdepth:
            try:
                html = lxml.html.fromstring(text)
            except Exception as exc:
                logger.error(
                    'prefetch (%s): error parsing %s: %s' % (depth, url, exc))
                continue
            html.make_links_absolute(url)
            for element, attribute, link, pos in html.iterlinks():
                if (attribute.lower() == 'href' and link.endswith('/') and
                        link not in visited):
                    to_visit.append((link, depth + 1)) 
Example #6
Source File: models.py    From opensurfaces with MIT License 5 votes vote down vote up
def external_task_url(self):
        if settings.ENABLE_SSL:
            # SSL certificates are under the host name
            base_url = settings.SITE_URL
        else:
            # use raw IP for faster page loads -- a fresh DNS lookup can take
            # as long as 6s in India for some DNS servers
            base_url = 'http://' % settings.SERVER_IP
        return base_url + reverse('mturk-external-task', args=(self.id,)) 
Example #7
Source File: models.py    From byro with Apache License 2.0 5 votes vote down vote up
def get_url(self):
        config = Configuration.get_solo()
        relative_url = reverse(
            "public:memberpage:member.dashboard",
            kwargs={"secret_token": self.secret_token},
        )
        if config.public_base_url:
            return urljoin(config.public_base_url, relative_url)
        else:
            return urljoin(settings.SITE_URL, relative_url) 
Example #8
Source File: forms.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def _sign(self, q, a, expires):
        plain = [getattr(settings, "SITE_URL", ""), settings.SECRET_KEY, q, a, expires]
        plain = "".join([str(p) for p in plain])
        return sha1(plain.encode("utf-8")).hexdigest() 
Example #9
Source File: feeds.py    From pythonic-news with GNU Affero General Public License v3.0 5 votes vote down vote up
def item_author_link(self, item):
        return settings.SITE_URL + item.user.get_absolute_url() 
Example #10
Source File: context_processors.py    From pythonic-news with GNU Affero General Public License v3.0 5 votes vote down vote up
def settings_context_processor(request):
   return {
       'SITE_NAME': settings.SITE_NAME,
       'SITE_DOMAIN': settings.SITE_DOMAIN,
       'SITE_URL': settings.SITE_URL
   } 
Example #11
Source File: models.py    From MetaCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_external_url(self):
        url = "{}{}".format(settings.SITE_URL, self.get_absolute_url())
        return url 
Example #12
Source File: contact.py    From oldp with MIT License 5 votes vote down vote up
def report_content_url(context):
    """
    Get URL to report content form with the current URL attached to it
    """
    request = context['request']

    # We use only the path here, ignoring all GET parameters
    source_url = settings.SITE_URL + request.path

    return reverse('contact:report_content') + '?source=' + quote_plus(source_url) 
Example #13
Source File: views.py    From micro-finance with MIT License 4 votes vote down vote up
def client_loan_application(request, client_id):
    form = LoanAccountForm()
    client = get_object_or_404(Client, id=client_id)
    group = Group.objects.filter(clients__id__in=client_id).first()
    account_no = unique_random_number(LoanAccount)
    loan_pay = LoanRepaymentEvery.objects.all()
    if request.method == 'POST':
        form = LoanAccountForm(request.POST)
        if form.is_valid():
            loan_account = form.save(commit=False)
            loan_account.status = "Applied"
            loan_account.created_by = User.objects.get(username=request.user)
            loan_account.client = client
            interest_charged = d(
                (
                    d(loan_account.loan_amount) * (
                        d(loan_account.annual_interest_rate) / 12)
                ) / 100
            )
            loan_account.principle_repayment = d(
                int(loan_account.loan_repayment_every) * (
                    d(loan_account.loan_amount) / d(
                        loan_account.loan_repayment_period)
                )
            )
            loan_account.interest_charged = d(
                int(loan_account.loan_repayment_every) * d(interest_charged))
            loan_account.loan_repayment_amount = d(
                d(loan_account.principle_repayment) + d(
                    loan_account.interest_charged)
            )
            loan_account.total_loan_balance = d(d(loan_account.loan_amount))
            if group:
                loan_account.group = group
            loan_account.save()

            if client.email and client.email.strip():
                send_email_template(
                    subject="Your application for the Personal Loan (ID: %s) has been Received." % loan_account.account_no,
                    template_name="emails/client/loan_applied.html",
                    receipient=client.email,
                    ctx={
                        "client": client,
                        "loan_account": loan_account,
                        "link_prefix": settings.SITE_URL,
                    },
                )
            return JsonResponse({"error": False, "loanaccount_id": loan_account.id})
        else:
            return JsonResponse({"error": True, "message": form.errors})
    context = {
        'form': form, 'client': client, 'account_no': account_no,
        'loan_repayment_every': loan_pay
    }
    return render(request, "client/loan/application.html", context) 
Example #14
Source File: views.py    From micro-finance with MIT License 4 votes vote down vote up
def change_loan_account_status(request, pk):
    # if request.method == 'POST':
        loan_object = get_object_or_404(LoanAccount, id=pk)
        if loan_object:
            branch_id = loan_object.group.branch.id
        elif loan_object.client:
            branch_id = loan_object.client.branch.id
        else:
            branch_id = None
        if branch_id:
            if (request.user.is_admin or
                (request.user.has_perm("branch_manager") and
                 request.user.branch.id == branch_id)):
                status = request.GET.get("status")
                if status in ['Closed', 'Withdrawn', 'Rejected', 'Approved']:
                    loan_object.status = request.GET.get("status")
                    loan_object.approved_date = datetime.datetime.now()
                    loan_object.save()
                    if loan_object.client:
                        if loan_object.status == 'Approved':
                            if loan_object.client.email and loan_object.client.email.strip():
                                send_email_template(
                                    subject="Your application for the Personal Loan (ID: %s) has been Approved." % loan_object.account_no,
                                    template_name="emails/client/loan_approved.html",
                                    receipient=loan_object.client.email,
                                    ctx={
                                        "client": loan_object.client,
                                        "loan_account": loan_object,
                                        "link_prefix": settings.SITE_URL,
                                    },
                                )

                    elif loan_object.group:
                        group_member_loans = GroupMemberLoanAccount.objects.filter(group_loan_account=loan_object)
                        group_member_loans.update(status=loan_object.status)
                        group_member_loans.update(loan_issued_date=loan_object.loan_issued_date)
                        group_member_loans.update(interest_type=loan_object.interest_type)
                        for client in loan_object.group.clients.all():
                            if client.email and client.email.strip():
                                send_email_template(
                                    subject="Group Loan (ID: %s) application has been Approved."
                                            % loan_object.account_no,
                                    template_name="emails/group/loan_approved.html",
                                    receipient=client.email,
                                    ctx={
                                        "client": client,
                                        "loan_account": loan_object,
                                        "link_prefix": settings.SITE_URL,
                                    },
                                )
                    data = {"error": False}
                else:
                    data = {"error": True, "error_message": "Status is not in available choices"}
            else:
                data = {"error": True, "error_message": "You don't have permission to change the status."}
        else:
            data = {"error": True, "error_message": "Branch Id not Found"}

        data["success_url"] = reverse('loans:clientloanaccount', kwargs={"pk": loan_object.id})
        return JsonResponse(data) 
Example #15
Source File: views.py    From shortweb with MIT License 4 votes vote down vote up
def shorten_url(request):
	url = request.POST.get("url", '')
	alias = request.POST.get("alias")
	valid_url,url=validate_url(url)
	if valid_url:
		if alias !='':
			for rec in record:
				if record[rec]==alias:
					return HttpResponse(json.dumps({"error":"error occurs", 'alias':-1, 'url':url}),content_type="application/json")

		if url in record:
			short_id = record.get(url)
			if alias !='' and alias != short_id:
				b = urls.objects.get(pk=short_id)
				b.short_id=alias
				b.save()		
				short_id = alias
				record[url]=alias
			response_data = {}
			response_data['url'] = settings.SITE_URL + "/" + short_id
			return HttpResponse(json.dumps(response_data),  content_type="application/json")
		else:
			# check whether input is already short
			if is_already_short(url):
				response_data = {}
				return HttpResponse(json.dumps({"already_short": True}), content_type="application/json")
			elif alias == '':
				short_id = get_short_code()
				record.update({url:short_id})
				b = urls(httpurl=url, short_id=short_id)
				b.save()
				response_data = {}
				response_data['url'] = settings.SITE_URL + "/" + short_id
				return HttpResponse(json.dumps(response_data),  content_type="application/json")

			else:
				record.update({url:alias})
				b = urls(httpurl=url, short_id=alias)
				b.save()
				response_data={}
				response_data['url'] = settings.SITE_URL + "/" + alias
				return HttpResponse(json.dumps(response_data),  content_type="application/json")
	return HttpResponse(json.dumps({"error": "error occurs", "valid_url":valid_url,'url':url}), content_type="application/json")