Django—如何简单地获取域名?(复制)

时间:2022-12-04 08:20:43

This question already has an answer here:

这个问题已经有了答案:

Firstly, I want to say that I'm a beginner in Django.

首先,我想说我是Django的初学者。

I'm looking for a simple way to retrieve the domain name of my Django website.

我正在寻找一个简单的方法来检索我的Django网站的域名。

I want to do this in my settings.py. I've already tried with the socket something like this:

我想在setter中这样做。我已经试过这样的插座了:

socket.gethostname()

socket.gethostname()

but this doesn't work correctly.

但这并不正确。

3 个解决方案

#1


12  

If you have a request object,do

如果您有一个请求对象,请执行

request.META['HTTP_HOST']

This would return the hostname

这将返回主机名

#2


7  

If you're using django.contrib.sites framework:

如果你使用django.contrib。网站的框架:

from django.contrib.sites.models import Site

your_domain = Site.objects.get_current().domain

Reference: https://docs.djangoproject.com/en/1.8/ref/contrib/sites/

参考:https://docs.djangoproject.com/en/1.8/ref/contrib/sites/

#3


0  

import platform
platform.node()

from the docs:

从文档:

"Returns the computer’s network name (may not be fully qualified!). An empty string is returned if the value cannot be determined."

返回计算机的网络名(可能不完全符合条件!)如果不能确定值,则返回一个空字符串。

#1


12  

If you have a request object,do

如果您有一个请求对象,请执行

request.META['HTTP_HOST']

This would return the hostname

这将返回主机名

#2


7  

If you're using django.contrib.sites framework:

如果你使用django.contrib。网站的框架:

from django.contrib.sites.models import Site

your_domain = Site.objects.get_current().domain

Reference: https://docs.djangoproject.com/en/1.8/ref/contrib/sites/

参考:https://docs.djangoproject.com/en/1.8/ref/contrib/sites/

#3


0  

import platform
platform.node()

from the docs:

从文档:

"Returns the computer’s network name (may not be fully qualified!). An empty string is returned if the value cannot be determined."

返回计算机的网络名(可能不完全符合条件!)如果不能确定值,则返回一个空字符串。