【问题标题】:How to serve data on every view at every URL endpoint如何在每个 URL 端点的每个视图上提供数据
【发布时间】:2018-02-02 12:27:05
【问题描述】:

我希望在每个 URL 端点提供相同视图的原因是视图将通知信息发送给经过身份验证的用户。
例如,这是一个视图,其中包含我希望在每个页面中提供的数据:

class NotificationsView(View):
    def get(self, request, *args, **kwargs):
        profile = Profile.objects.get(user__username=self.request.user)
        notifs = profile.user.notifications.unread()
        return render(request, 'base.html', {'notifs': notifs})

我正在尝试将上下文变量发送到我的模板中以与 javascript 一起使用。 JS 文件与模板分开,所以我尝试先在基本模板中声明全局 JS 变量,然后在 JS 文件中使用它们。

base.html:

  ...
  {% include "landing/notifications.html" %}
  <script src="{% static 'js/notify.js' %}" type="text/javascript"></script>
  {% register_notify_callbacks callbacks='fill_notification_list, fill_notification_badge' %}  

登陆/notifications.html:

<script type="text/javascript">
    var myuser = '{{request.user}}';
    var notifications  = '{{notifs}}';
</script>  

通知.js:

...
return '<li><a href="/">' + myuser + notifications + '</a></li>';
        }).join('')
    }
}  

基于此代码,您可以看到我是如何陷入困境的,我需要使用 CBV 将正确的通知发送到landing/notifications.html 以确保 javascript 变量可以动态为 JS 文件渲染。

我完全不知道应该如何连接 URL。
像这样:

url(
        regex=r'^notes$',
        view=views.NotificationsView.as_view(),
        name='home'
    ),  

将我限制在特定的端点(“/notes”)。

你建议我如何解决这个问题?

【问题讨论】:

    标签: django django-templates django-views django-notification


    【解决方案1】:

    这看起来对上下文处理器很有用!无论视图和路线如何,它们都会在整个项目中添加上下文变量。以下是一些可能有帮助的阅读和示例代码:

    django context processor

    https://docs.djangoproject.com/en/2.0/ref/templates/api/#django.template.RequestContext

    https://docs.djangoproject.com/en/2.0/topics/templates/#configuration

    myproject.context_processors.py

    def notifications(request):
        try:
            profile = Profile.objects.get(user__username=self.request.user)
            return {'notifs': profile.user.notifications.unread()}
        except Profile.DoesNotExist:
            return {}
    

    myproject.settings.py

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',  # default
            'DIRS': [],  # default
            'APP_DIRS': True,  # default
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',  # default
                    'django.template.context_processors.request',  # default
                    'django.contrib.auth.context_processors.auth',  # default
                    'django.contrib.messages.context_processors.messages',  # default
                    'myproject.context_processors.notifications'  # your context processor
                ]
            }
        }
    ]
    

    【讨论】:

      【解决方案2】:

      您可以像这样使用网址:

      url(r'/s*', test, name='test'),
      

      看看official docsthis link

      【讨论】:

      • 这个正则表达式是什么意思?
      • 我想这意味着任何字符串。
      • 这会将每个 URL 端点仅重定向到该单个视图。也许我应该澄清一下,我还有其他使用其他端点的视图。
      【解决方案3】:

      您想要的可以总结如下:在应用的每个页面中添加一个子模板(您的通知模板,数据从数据库中获取)。

      看看这个问题:Django - two views, one page

      例如,您可以为视图创建一个 mixin,其中包括模板上下文中的通知,如下所示:

      myview.html

      <div>
      {% include "notifications.html" %}  
      <!-- Handle data from my view-->  
      </div>
      

      notifications.html:

      <ul>
      {% for notification in notifications %}
          <li><a href=""><!-- Your notif data --></a></li>
      {% endfor %}
      </ul>
      

      【讨论】:

        猜你喜欢
        • 2011-10-26
        • 1970-01-01
        • 2019-11-13
        • 2018-10-09
        • 2014-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多