0

我正在使用 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。

4

3 回答 3

5

我想你想要user.get_profile()

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

于 2012-04-29T22:00:51.363 回答
1

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

  1. 用户对象可通过模板中的“django.contrib.auth.context_processors.auth”上下文处理器获得。
  2. 正如您可以在 django 模板上下文中使用可用 Python 对象的所有方法一样,User.get_profile() 方法可用。

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

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 } )                                    
于 2012-04-29T23:26:21.527 回答
1

您也可以在您的用户配置文件应用程序 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])

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

于 2012-05-01T13:39:25.703 回答