Wagtail始终使用默认站点的URL。

huangapple go评论79阅读模式
英文:

Wagtail always uses default site for URLs

问题

我正在使用Django网站框架和Wagtail。Wagtail正确地为每个站点提供了我指定的设置。我目前注册了两个站点:127.0.0.1和172.1.16.155。

所以,当我访问127.0.0.1时,我会得到127.0.0.1的所有站点设置,反之亦然。问题是,我将172.1.16.155设置为默认站点。当我从127.0.0.1导航到一个URL(例如:127.0.0.1:8080/home/),它会跳转到172.1.16.1(172.1.16.155:8080/home/),如果我将默认站点设置为回环地址,情况也是一样。

我尝试过使用page.full_urlpage.url,但都没有成功。我还尝试将http://127.0.0.1添加到站点设置中(尽管我知道这是不正确的),但也没有成功。

我在两个站点上使用相同的根目录。这是我的项目要求,因为我需要显示相同的页面,无论域名如何,但每个域名上的图标等必须不同。这个是可以工作的。只是HTML中包含的锚点标签会将我带到当前所在域之外。

以下是一些可能相关的Django设置:

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env("SECRET_KEY",default="django-insecure-#=($lwdhz$drt5@h752_puh!y^5aqxh!bn($t_$^x(qd#1p5=e")

DEBUG = str(env("DEBUG", default="False")).lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']

SECURE_CROSS_ORIGIN_OPENER_POLICY = None

ALLOWED_HOSTS = env("DJANGO_ALLOWED_HOSTS",default="127.0.0.1 localhost").split(" ")
CSRF_TRUSTED_ORIGINS = env("CSRF_TRUSTED_ORIGINS",default="http://127.0.0.1 http://localhost").split(" ")

# Search
# https://docs.wagtail.org/en/stable/topics/search/backends.html
WAGTAILSEARCH_BACKENDS = {
    "default": {
        "BACKEND": "wagtail.search.backends.database",
    }
}

# Base URL to use when referring to full URLs within the Wagtail admin backend -
# e.g. in notification emails. Don't include '/admin' or a trailing slash
WAGTAILADMIN_BASE_URL = env("WAGTAILADMIN_BASE_URL", "http://127.0.0.1:8080")
WAGTAIL_SITE_NAME = env("WAGTAIL_SITE_NAME", "flex")


# Application definition
INSTALLED_APPS = [
    "flex.apps.FlexConfig",
    "blog.apps.BlogConfig",
    'reviews.apps.ReviewsConfig',
    "contact.apps.ContactConfig",
    "search",

    'wagtail_color_panel',

    "site_settings.apps.SiteSettingsConfig",
    "wagtail.contrib.settings",


    "wagtail.contrib.forms",
    "wagtail.contrib.redirects",
    "wagtail.embeds",
    "wagtail.sites",
    "wagtail.users",
    "wagtail.snippets",
    "wagtail.documents",
    "wagtail.images",
    "wagtail.search",
    "wagtail.admin",
    "wagtail.contrib.modeladmin",
    'treemodeladmin',

    "wagtail",
    "modelcluster",
    "taggit",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

WAGTAILIMAGES_EXTENSIONS = ["gif", "jpg", "jpeg", "png", "webp", "svg"]

MIDDLEWARE = [
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "wagtail.contrib.redirects.middleware.RedirectMiddleware",
]

ROOT_URLCONF = "core.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [
            os.path.join(PROJECT_DIR, "templates"),
        ],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
                'wagtail.contrib.settings.context_processors.settings',
            ],
            "builtins": [
                "core.templatetags.core_tags",
            ],
        },
    },
]

为了调试目的,我在wagtail的get_url方法中添加了打印语句,如下所示:

    def get_url(self, request=None, current_site=None):
        """
        Return the 'most appropriate' URL for referring to this page from the pages we serve,
        within the Wagtail backend and actual website templates;
        this is the local URL (starting with '/') if we're only running a single site
        (i.e. we know that whatever the current page is being served from, this link will be on the
        same domain), and the full URL (with domain) if not.
        Return None if the page is not routable.

        Accepts an optional but recommended ``request`` keyword argument that, if provided, will
        be used to cache site-level URL information (thereby avoiding repeated database / cache
        lookups) and, via the ``Site.find_for_request()`` function, determine whether a relative
        or full URL is most appropriate.
        """
        # ``current_site`` is purposefully undocumented, as one can simply pass the request and get
        # a relative URL based on ``Site.find_for_request()``. Nonetheless, support it here to avoid
        # copy/pasting the code to the ``relative_url`` method below.
        print("getting url")
        if current_site is None and request is not None:
            site = Site.find_for_request(request)
            current_site = site
            print("site", site)

        print("current_site", current_site) # None
        # print(current_site, request, request.get_host() if request is not None else None) # None None None
        url_parts = self.get_url_parts(request=request)

        print("url_parts", url_parts)
        ....

以及在find_for_request方法中:

    @staticmethod
    def find_for_request(request):
        if request is None:
            return None
        if not hasattr(request, "_wagtail_site"):
            site = Site._find_for_request(request)
            setattr(request, "_wagtail_site", site)

        print("Site: from_request", request._wagtail_site)
        return request._wagtail_site

这为我提供了以下终端输出:

System check identified no issues (0 silenced).
August 08, 2023 - 15:10:33
Django version 4.2.1, using settings 'core.settings'
Starting development server at http://0.0.0.0:8080/
Quit the server with CTRL-BREAK.

Site: from_request Localhost
Site: from_request Localhost
Site: from_request Localhost
Site: from_request Localhost
Site: from_request Localhost
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/autoschade/') # 我从127.0.0.1导航
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/caravan-en-camperschade/')# 我从127.0.0.1导航
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/ruitschade/')# 我从127.0.0.1导航
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/banden/')# 我从127.0.0.1导航
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/over-ons/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/duurzaamheid/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/abs-actueel/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/autoschade/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/ruitschade/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/caravan-en-camperschade/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/banden/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/opdrachtgevers/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/abs-actueel/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/caravan-en-camperschade/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/ruitschade/')
[08/Aug/2023 15:10:33] "GET / HTTP/1.1" 200 26173
[08/Aug/2023 15:10:33] "GET /static/css/core.css HTTP/1.1" 200 6927
[08/Aug/2023 15:10:33] "GET /static/css/bootstrap.min.css HTTP/1.1" 200 241729
[08/Aug/2023 15:10:33] "GET /static/js/bold-and-bright.js HTTP/1.1" 200 1395
[08/Aug/2023 15:10:33] "GET /static/js/core.js HTTP/1.1" 200 12097
[08/Aug/2023 15:10:33] "GET /static/js/bootstrap.min.js HTTP/1.1" 200 80372
[08/Aug/2023 15:10:33] "GET /media/images/slide-01-home.scale-100.jpg HTTP/1.1" 200 203911
[08/Aug/2023 15:10:33] "GET /media/images/Beckers_en_mulder_0000_BeckersMulder_W1C2171.scale-100.jpg HTTP/1.1" 200 181518
[08/Aug/2023 15:10:33] "GET /media/images/Beckers_en_mulder_0015_BeckersMulder_W1C1873_c.scale-100.jpg HTTP/1.1" 200 127941
[08/Aug/2023 15:10:33] "GET /media/images/anwb.width-200.svg HTTP/1.1" 200 6256
[08/Aug/2023 15:10:33] "GET /media/images/interpolis.width-200.svg HTTP/1.1" 200 7216
[08/Aug/2023 15:10:33] "GET /media/images/icon-caravan-500.scale-100.png HTTP/1.1" 200 64961
[08/Aug/2023 15:10:33] "GET /media/images/icon-ruitschade-500.scale-100.png HTTP/1.1" 200 54691
[08/Aug/2023 15:10:33] "GET /media/images/icon-autoschade-500.scale-100.png HTTP/1.1" 200 80444
[08/Aug/2023 15:10:33] "GET /media/images/icon-banden-500.scale-100.png HTTP/1.1" 200 68924
[08/Aug/2023 15:10:33] "GET /media/images/alphabet.width-200.svg HTTP/1.1" 200 5460
[08/Aug/2023 15:10:33] "GET /media/images/HEMA.width-200.svg HTTP/1.1" 200 1148
[08/Aug/2023 15:10:33] "GET /media/images/wave-pattern-2.original.svg HTTP/1.1" 200 747
Site: from_request Localhost
Site: from_request Localhost
Not Found: /favicon.ico
[08/Aug/2023 15:10:33] "GET /favicon.ico HTTP/1.1" 404 3472
英文:

I am using the Django site framework with wagtail.
Wagtail correctly gives me the settings I specified for each site.
I as of now have 2 sites registered:

127.0.0.1
172.1.16.155

So, when I visit 127.0.0.1, I get all the site settings for 127.0.0.1, and vice versa.
The issue is, I have 172.1.16.155 as my default site. When I navigate to a URL from 127.0.0.1, (example: 127.0.0.1:8080/home/) it will go to 172.1.16.1 (172.1.16.155:8080/home/), and the same thing the other way around if I set the default site to the loopback addr.

I have tried using both page.full_url and page.url, but to no avail.
I have tried adding http://127.0.0.1 to the site settings (though I know this is incorrect), also to no avail.

I am using the same root for both sites.
This is a requirement for my project, as I require the same pages to be displayed no matter the domain, but the icons and such must differ on each domain. This works. It's just that the HTML contains anchor tags which lead me off the domain I am currently on.

Some possibly relevant Django settings:

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env("SECRET_KEY",default="django-insecure-#=($lwdhz$drt5@h752_puh!y^5aqxh!bn($t_$^x(qd#1p5=e")

DEBUG = str(env("DEBUG", default="False")).lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']

SECURE_CROSS_ORIGIN_OPENER_POLICY = None

ALLOWED_HOSTS = env("DJANGO_ALLOWED_HOSTS",default="127.0.0.1 localhost").split(" ")
CSRF_TRUSTED_ORIGINS = env("CSRF_TRUSTED_ORIGINS",default="http://127.0.0.1 http://localhost").split(" ")

# Search
# https://docs.wagtail.org/en/stable/topics/search/backends.html
WAGTAILSEARCH_BACKENDS = {
    "default": {
        "BACKEND": "wagtail.search.backends.database",
    }
}

# Base URL to use when referring to full URLs within the Wagtail admin backend -
# e.g. in notification emails. Don't include '/admin' or a trailing slash
WAGTAILADMIN_BASE_URL = env("WAGTAILADMIN_BASE_URL", "http://127.0.0.1:8080")
WAGTAIL_SITE_NAME = env("WAGTAIL_SITE_NAME", "flex")


# Application definition
INSTALLED_APPS = [
    "flex.apps.FlexConfig",
    "blog.apps.BlogConfig",
    'reviews.apps.ReviewsConfig',
    "contact.apps.ContactConfig",
    "search",

    'wagtail_color_panel',

    "site_settings.apps.SiteSettingsConfig",
    "wagtail.contrib.settings",


    "wagtail.contrib.forms",
    "wagtail.contrib.redirects",
    "wagtail.embeds",
    "wagtail.sites",
    "wagtail.users",
    "wagtail.snippets",
    "wagtail.documents",
    "wagtail.images",
    "wagtail.search",
    "wagtail.admin",
    "wagtail.contrib.modeladmin",
    'treemodeladmin',

    "wagtail",
    "modelcluster",
    "taggit",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

WAGTAILIMAGES_EXTENSIONS = ["gif", "jpg", "jpeg", "png", "webp", "svg"]

MIDDLEWARE = [
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "wagtail.contrib.redirects.middleware.RedirectMiddleware",
]

ROOT_URLCONF = "core.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [
            os.path.join(PROJECT_DIR, "templates"),
        ],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
                'wagtail.contrib.settings.context_processors.settings',
            ],
            "builtins": [
                "core.templatetags.core_tags",
            ],
        },
    },
]

For debugging purposes I have added print statements to the wagtail get_url method, like so:

    def get_url(self, request=None, current_site=None):
"""
Return the 'most appropriate' URL for referring to this page from the pages we serve,
within the Wagtail backend and actual website templates;
this is the local URL (starting with '/') if we're only running a single site
(i.e. we know that whatever the current page is being served from, this link will be on the
same domain), and the full URL (with domain) if not.
Return None if the page is not routable.
Accepts an optional but recommended ``request`` keyword argument that, if provided, will
be used to cache site-level URL information (thereby avoiding repeated database / cache
lookups) and, via the ``Site.find_for_request()`` function, determine whether a relative
or full URL is most appropriate.
"""
# ``current_site`` is purposefully undocumented, as one can simply pass the request and get
# a relative URL based on ``Site.find_for_request()``. Nonetheless, support it here to avoid
# copy/pasting the code to the ``relative_url`` method below.
print("getting url")
if current_site is None and request is not None:
site = Site.find_for_request(request)
current_site = site
print("site", site)
print("current_site", current_site) # None
# print(current_site, request, request.get_host() if request is not None else None) # None None None
url_parts = self.get_url_parts(request=request)
print("url_parts", url_parts)
....

and inside find_for_request:

    @staticmethod
def find_for_request(request):
if request is None:
return None
if not hasattr(request, "_wagtail_site"):
site = Site._find_for_request(request)
setattr(request, "_wagtail_site", site)
print("Site: from_request", request._wagtail_site)
return request._wagtail_site

this provides me with the following terminal output:

System check identified no issues (0 silenced).
August 08, 2023 - 15:10:33
Django version 4.2.1, using settings 'core.settings'
Starting development server at http://0.0.0.0:8080/
Quit the server with CTRL-BREAK.

Site: from_request Localhost
Site: from_request Localhost
Site: from_request Localhost
Site: from_request Localhost
Site: from_request Localhost
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/autoschade/') # I AM NAGIVATING FROM 127.0.0.1
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/caravan-en-camperschade/')# I AM NAGIVATING FROM 127.0.0.1
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/ruitschade/')# I AM NAGIVATING FROM 127.0.0.1
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/banden/')# I AM NAGIVATING FROM 127.0.0.1
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/over-ons/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/duurzaamheid/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/abs-actueel/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/autoschade/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/ruitschade/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/caravan-en-camperschade/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/banden/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/opdrachtgevers/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/abs-actueel/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/caravan-en-camperschade/')
getting url
current_site None
url_parts (2, 'http://172.16.1.155:8080', '/ruitschade/')
[08/Aug/2023 15:10:33] "GET / HTTP/1.1" 200 26173
[08/Aug/2023 15:10:33] "GET /static/css/core.css HTTP/1.1" 200 6927
[08/Aug/2023 15:10:33] "GET /static/css/bootstrap.min.css HTTP/1.1" 200 241729
[08/Aug/2023 15:10:33] "GET /static/js/bold-and-bright.js HTTP/1.1" 200 1395
[08/Aug/2023 15:10:33] "GET /static/js/core.js HTTP/1.1" 200 12097
[08/Aug/2023 15:10:33] "GET /static/js/bootstrap.min.js HTTP/1.1" 200 80372
[08/Aug/2023 15:10:33] "GET /media/images/slide-01-home.scale-100.jpg HTTP/1.1" 200 203911
[08/Aug/2023 15:10:33] "GET /media/images/Beckers_en_mulder_0000_BeckersMulder_W1C2171.scale-100.jpg HTTP/1.1" 200 181518
[08/Aug/2023 15:10:33] "GET /media/images/Beckers_en_mulder_0015_BeckersMulder_W1C1873_c.scale-100.jpg HTTP/1.1" 200 127941
[08/Aug/2023 15:10:33] "GET /media/images/anwb.width-200.svg HTTP/1.1" 200 6256
[08/Aug/2023 15:10:33] "GET /media/images/interpolis.width-200.svg HTTP/1.1" 200 7216
[08/Aug/2023 15:10:33] "GET /media/images/icon-caravan-500.scale-100.png HTTP/1.1" 200 64961
[08/Aug/2023 15:10:33] "GET /media/images/icon-ruitschade-500.scale-100.png HTTP/1.1" 200 54691
[08/Aug/2023 15:10:33] "GET /media/images/icon-autoschade-500.scale-100.png HTTP/1.1" 200 80444
[08/Aug/2023 15:10:33] "GET /media/images/icon-banden-500.scale-100.png HTTP/1.1" 200 68924
[08/Aug/2023 15:10:33] "GET /media/images/alphabet.width-200.svg HTTP/1.1" 200 5460
[08/Aug/2023 15:10:33] "GET /media/images/HEMA.width-200.svg HTTP/1.1" 200 1148
[08/Aug/2023 15:10:33] "GET /media/images/wave-pattern-2.original.svg HTTP/1.1" 200 747
Site: from_request Localhost
Site: from_request Localhost
Not Found: /favicon.ico
[08/Aug/2023 15:10:33] "GET /favicon.ico HTTP/1.1" 404 3472

答案1

得分: 1

page.full_urlpage.url属性无法访问当前请求对象,因此它们无法优先考虑您当前访问页面的站点。

在模板代码中,您应该使用{% pageurl %}模板标签 - 它从模板上下文中获取当前请求,从而允许它相应地调整生成的URL。在其他地方(例如get_context方法中),您可以使用Page.get_url方法代替。

英文:

The page.full_url and page.url properties have no access to the current request object, so there's no way for them to give preference to the site you're currently accessing the page from.

Within template code, you should use the {% pageurl %} template tag - this picks up the current request from the template context, allowing it to adjust the resulting URL accordingly. Elsewhere (such as within a get_context method), you can use the Page.get_url method instead.

huangapple
  • 本文由 发表于 2023年8月8日 21:02:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76859841.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定