【问题标题】:Django {{ profile }} globally available in templatesDjango {{ profile }} 在模板中全局可用
【发布时间】:2012-05-09 17:09:50
【问题描述】:

我正在使用 django-registration 和 django-profiles 构建应用程序。在页面的任何地方,我都有显示当前登录用户数据的部分(如名字和姓氏,使用如下语法:{{ user.first_name }}),它工作正常。它是通过 子页面模板来扩展一个具有 HTML 结构的主模板 和提到的部分来完成的。

现在我尝试将用户图像(使用{{ profile.image }})添加到该部分,但在以下页面上,{{ profile }} 模板变量的可用性存在问题:

settings.py 我有:

AUTH_PROFILE_MODULE = 'intranet.UserProfile'

TEMPLATE_CONTEXT_PROCESSORS = (
   'django.core.context_processors.static',
)

"django.contrib.auth.context_processors.auth", 添加到TEMPLATE_CONTEXT_PROCESSORS 不会改变任何内容。

我在 models.py 中的 UserProfile 类是:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    image = models.ImageField(upload_to=user_image_name,
        blank=True, null=True, verbose_name='User photo')

urls.py

(r'^profiles/edit/', 'profiles.views.edit_profile', {'form_class': ProfileForm, }),
(r'^profiles/', include('profiles.urls')),

所以其余的默认设置在 django-profiles urls.py 文件中。

我希望能够在应用程序的模板中使用{{ profile }}随处可见的模板变量(不仅在个人资料页面上),以便能够在其他人扩展的主模板中使用它。

请告诉我如何获得这个。任何帮助将不胜感激。

我在 1.3.1 版中使用 Django,在 0.7 版中使用 django-registration,在 0.2 版中使用 django-profiles。

【问题讨论】:

    标签: django templates django-templates profiles django-profiles


    【解决方案1】:

    我想你想要user.get_profile()

    如果您使用的是RequestContext,并且settings.py 的上下文处理器列表中有auth,请尝试{{user.get_profile.image}},看看它是否符合您的要求。

    【讨论】:

      【解决方案2】:

      我认为“彼得·罗威尔”的上述回答在这种特定情况下一定对你有用,原因如下,

      1. 模板中的“django.contrib.auth.context_processors.auth”上下文处理器可以使用用户对象。
      2. 因为您可以在 django 模板上下文中使用可用 Python 对象的所有方法,所以 User.get_profile() 方法可用。

      但是如果您在模板中需要任何其他对象(例如,id=2 的条目对象,或者如果您没有 "django.contrib.auth.context_processors.auth" ),您可以在字典中提供任何对象从您的视图模板如下

      def view_needing_profile(request):
          c_user = request.user
          c_profile = c_user.get_profile()
          c_entry = Entry.objects.get(id=2)
      
          return render(request, 'template_using_profile_and_entry.html',
                                 {'profile' : c_profile, 'entry' : c_entry } )                                    
      

      【讨论】:

        【解决方案3】:

        您也可以在您的用户配置文件应用程序 models.py 文件中添加类似的内容

        # Fetches the user profile if it exists, otherwise, it creates one User.get_or_create_profile = property(lambda u: Profile.objects.get_or_create(user=u)[0])

        这可确保您始终返回配置文件对象。

        【讨论】:

          猜你喜欢
          • 2011-01-14
          • 2010-11-05
          • 1970-01-01
          • 1970-01-01
          • 2020-05-12
          • 2011-05-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多