Django配置文件 - 向详细视图添加额外的对象

时间:2011-07-19 08:40:19

标签: django

在扩展了优秀的django项目django-profiles(在https://bitbucket.org/ubernostrum/django-profiles/wiki/Home上找到)后,我偶然发现了一些我几天试图解决的问题。

这个想法很简单。我有用户,其中包含用户配置文件(对象UserProfile,链接到User)。现在我在我的项目Employment中添加了一个新对象,它也链接到User对象。

class Employment(models.Model):
    """
    A class to describe the relationship of employment, past or present, between an employee and an organization.

    """

    def __unicode__(self):
        return self.function

    def get_absolute_url(self):
        return "/recycling/employment/%i/" % self.id

    user = models.ForeignKey(User)
    organization = models.ForeignKey(Organization)
    date_start = models.DateField('Start date of employment', help_text="Please use the following format: YYYY-MM-DD.", null=True, blank=True)
    date_end = models.DateField('End date of employment', help_text="Please use the following format: YYYY-MM-DD.", null=True, blank=True)
    function = models.CharField(max_length=100)
    present_job = models.BooleanField()


class UserProfile(models.Model):
    """
    A class representing a the profile of a user.  Needs to be generic enough to involve both employees as employers.

    """

    def _get_absolute_url(self):
        return ('profiles_profile_detail', (), { 'username': self.user.username })

    # Link person to user
    user = models.ForeignKey(User, unique=True, null=True)

    registration_date = models.DateField(auto_now_add=True)

现在我想有一个页面(详细视图),我可以在其中显示UserProfile以及特定用户的所有工作。 我认为添加extra_context是可行的方法,例如:。

('^profiles/(?P<username>\w+)/$', 'profiles.views.profile_detail', {'extra_context': {'employment_list': Employment.objects.all(),}}), 

然而,我面临的问题是我想拥有特定于用户的对象(因此过滤)而不仅仅是所有()。 一个缺陷是django-profiles项目仍然使用函数作为视图而不是类,因此子类化不是一个选项。另一个注意点是视图不应该被缓存,因此如果用户添加另一个就业对象并被重定向到详细信息页面,则应该反映此更改。 如果不改编django-profiles代码本身就找到一个解决方案会很好...

感谢您的帮助!


找到了这样做的方法,结果证明相当简单。我创建了一个新视图,它生成一个带过滤器的列表。将extra_context中的此列表传递给配置文件应用程序中定义的视图并完成...

def detail_userprofile_view(request, username):
    """
    Returns a detail view including both the User Profile and the Employments linked to the user.
    """

    employment_list = Employment.objects.filter(user__username=username)
    context_dict = { 'employment_list': employment_list,}

    return profile_detail(request, username, extra_context=context_dict)

1 个答案:

答案 0 :(得分:0)

你总是可以写一个新视图。简单的事情:

网址

url(r'^profiles/(?P<username>\w+)/$', profiles.views.profile_detail, name='profile_detail'),

视图

def profile_detail(request, username):
    context_dict = {}
    user = get_object_or_404(User, username=username)
    profile = get_object_or_404(Profile, user=user)
    employment = get_object_or_404(Employment, user=user)

    context_dict = { 'user': user,
                     'profile':profile,
                     'employment':employment,
    }
    return render_to_response('details.html', context_dict, RequestContext(request))

现在,您可以在模板中{{ user.first_name }}{{ profile }}{{ employment.organization }}等等...

相关问题