首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sites框架是如何工作的?

sites框架是如何工作的?
EN

Stack Overflow用户
提问于 2017-11-16 08:32:29
回答 1查看 596关注 0票数 0

我正在尝试开发一个类似于站点框架的操作的ModelManager。根据用户的字段,ModelManager返回一个查询集。我试图模仿Sites Framework的操作,但我不明白如何使用此函数动态获取SITE_ID:

代码语言:javascript
复制
    def get_queryset(self):
    return super(CurrentSiteManager, self).get_queryset().filter(
        **{self._get_field_name() + '__id': settings.SITE_ID})

它似乎是静态的:/。

我通过中间件捕获用户的字段,并将其分配给request.field。如何检索ModelManager中字段并执行查询?

EN

回答 1

Stack Overflow用户

发布于 2017-11-16 09:25:32

我认为你错过了获取当前站点实例的动态方法。在documentation示例中:

代码语言:javascript
复制
from django.contrib.sites.shortcuts import get_current_site

def article_detail(request, article_id):
    try:
        a = Article.objects.get(id=article_id, 
            sites__id=get_current_site(request).id)
    except Article.DoesNotExist:
        raise Http404("Article does not exist on this site")
    # ...

您应该使用get_current_site方法来获取当前站点。

需要注意的是,如果你真的在SITE_ID=1这样的设置中定义了当前站点,那么它就不起作用了。

如果未定义SITE_ID设置,则

将根据request.get_host()查找当前站点。

你应该阅读this part of the documentation,它解释了django如何以动态的方式获取当前站点:

shortcuts.get_current_site(request)

检查是否安装了django.contrib.sites并根据请求返回当前Site对象或RequestSite对象的函数。如果未定义SITE_ID设置,它将基于request.get_host()查找当前站点。

当主机标头具有显式指定的端口时,request.get_host()可以同时返回域和端口。在这种情况下,如果由于主机与数据库中的记录不匹配而导致查找失败,则端口将被剥离,并且仅使用域部分重试查找。这不适用于始终使用未修改主机的RequestSite。

这是get_current_site实际调用的get_currentcode

代码语言:javascript
复制
def get_current(self, request=None):
    """
    Return the current Site based on the SITE_ID in the project's settings.
    If SITE_ID isn't defined, return the site with domain matching
    request.get_host(). The ``Site`` object is cached the first time it's
    retrieved from the database.
    """
    from django.conf import settings
    if getattr(settings, 'SITE_ID', ''):
        site_id = settings.SITE_ID
        return self._get_site_by_id(site_id)
    elif request:
        return self._get_site_by_request(request)

    raise ImproperlyConfigured(
        "You're using the Django \"sites framework\" without having "
        "set the SITE_ID setting. Create a site in your database and "
        "set the SITE_ID setting or pass a request to "
        "Site.objects.get_current() to fix this error."
    )
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47319637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档