网站框架如何运作?

时间:2017-11-16 00:32:29

标签: django django-sites

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

    def get_queryset(self):
    return super(CurrentSiteManager, self).get_queryset().filter(
        **{self._get_field_name() + '__id': settings.SITE_ID})

似乎是静态的:/。

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

1 个答案:

答案 0 :(得分:0)

我认为您缺少获取当前网站实例的动态方式。 来自documentation示例:

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(请求)

     

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

     

当Host头具有明确指定的端口时,request.get_host()可以返回域和端口,例如, example.com:80。在这种情况下,如果查找因主机与数据库中的记录不匹配而失败,则会剥离端口并仅使用域部分重试查找。这不适用于始终使用未修改主机的RequestSite。

以下是get_current实际调用的get_current_site的{​​{3}}:

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