一种在settings.py中具有django SITEURL常量的方法 [英] a way to have django SITEURL constant in settings.py
问题描述
我来自PHP背景,我知道可以在框架中的大多数地方访问常量,并且我认为在django中也是如此。我也尝试过在django中使用该URL,但是我尝试从django.contrib中使用它。我尝试利用django的Site类并将其导入。但是问题是,在加载settings.py时,我无法导入任何Django contrib。文件。
I am from PHP background, and I know that constants can be accessed at most of places in a framework and I think it is same in django as well. I tried to have that URL too in django but I tried to have it from django.contrib. I tried to utilize django's Site class and imported that. But the problem is that at time of loading settings.py I can't import any django contrib. file.
因此,如何自动拥有可在模板以及其他地方的任何地方使用的SITE URL。最佳方法是什么?是否有任何python实用程序可以这样做?
So how can I have SITE URL automatically that I can use anywhere, in template as well as at other places.What is the best way to do so? Do any python utility can do so?
推荐答案
无论您在settings.py中定义的内容如何,例如
Whatever you define in your settings.py, for example
SITE_URL = 'http://www.mydomain.com'
可以使用以下所有与Django相关的代码进行访问:
Can be accessed in all your Django related code with:
from django.conf import settings #this imports also your specific settings.py
print settings.SITE_URL
或者仅 Site.objects.get_current()。domain
如果您希望能够在模板中访问它,则可以自己创建<一个href = https://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors rel = noreferrer>模板上下文处理器。将其放入django.conf中的
If you want to be able to access it in the templates, you make your own template context processor. Put this in my_project/content_processor.py
from django.conf import settings
def my_site_url(request):
return {
'SITE_URL': settings.SITE_URL,
}
或者,如果您希望它是动态的:
Or if you want it Dynamic:
from django.conf import settings
def my_site_url(request):
return {
'SITE_URL': Site.objects.get_current().domain,
}
并将其添加到settings.py中的TEMPLATE_CONTEXT_PROCESSORS变量中。
And add it to your TEMPLATE_CONTEXT_PROCESSORS variable in settings.py. It should look similar to that afterwards:
TEMPLATE_CONTEXT_PROCESSORS =("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"my_project.context_processors.my_site_url",
)
并完成。
这篇关于一种在settings.py中具有django SITEURL常量的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!