a way to have django SITEURL constant in settings.py

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 01:20:35

问题


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.

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?


回答1:


Whatever you define in your settings.py, for example

SITE_URL = 'http://www.mydomain.com'

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

Or just Site.objects.get_current().domain

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,
    }

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",
)

and finished.



来源:https://stackoverflow.com/questions/12333548/a-way-to-have-django-siteurl-constant-in-settings-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!