如何获取Django中的URL(带有协议和域)(无请求)? [英] How can I get the URL (with protocol and domain) in Django (without request)?

查看:89
本文介绍了如何获取Django中的URL(带有协议和域)(无请求)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Cron作业中发送邮件。邮件中应包含指向我的应用程序的
a链接。

I want to send mails in a cron job. The mail should contain a link to my application.

在cron作业中,我没有请求对象,因此无法使用request.build_absolute_uri( )。

In cron job, I don't have a request object, and can't use request.build_absolute_uri().

AFAIK网站框架可以在这里提供帮助。

AFAIK the site framework can help here. But does not give me the protocol (http vs https)?

我的应用程序可重用,有时托管在http上,有时托管在https站点上。

My application is reusable and sometimes gets hosted on http and sometimes on https sites.

更新

我搜索一种通用的django方式。可以创建自定义设置,但是首选使用Django标准的解决方案。

I search a common django way. Creating custom settings is possible, but a solution with django standards is preferred.

相关问题: https://code.djangoproject.com/ticket/16734

推荐答案

此任务有一个特殊的标准模块-网站框架
它添加了站点模型,该模型描述了特定站点。该模型的项目域具有字段 domain name -网站的可读名称。

There's special standard module for this task - Sites Framework. It adds Site model, which describes specific site. This model has field domain for domain of the project, and a name - human-readable name of the site.

您将模型与站点相关联。像这样:

You associate your models with sites. Like so:

from django.db import models
from django.contrib.sites.models import Site

class Article(models.Model):
    headline = models.CharField(max_length=200)
    # ...
    site = models.ForeignKey(Site, on_delete=models.CASCADE)

当您需要为对象创建url时,可以使用以下代码:

When you need to make an url for the object you may use something like the following code:

   >>> from django.contrib.sites.models import Site
   >>> obj = MyModel.objects.get(id=3)
   >>> obj.get_absolute_url()
   '/mymodel/objects/3/'
   >>> Site.objects.get_current().domain
   'example.com'
   >>> 'https://%s%s' % (Site.objects.get_current().domain, obj.get_absolute_url())
   'https://example.com/mymodel/objects/3/'

这样,您可以拥有多个域并在它们之间传播内容。
即使您只有一个域,我还是建议您使用它来实现一种良好的标准舒适方式来保留域设置。

This way you can have multiple domains and content spread between them. Even if you have only one domain I recommend use it to achieve a good standard comfortable way to keep domain settings.

安装非常简单:


  1. 'django.contrib.sites'添加到您的 INSTALLED_APPS 设置。

定义SITE_ID设置:

Define a SITE_ID setting:

 SITE_ID = 1


  • 运行迁移。

  • Run migrate.

    这篇关于如何获取Django中的URL(带有协议和域)(无请求)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆