开发者

How to I lookup to fields in another table with the same parent (User) with Django templates?

I'm pretty new to Django and Python. I've been doing a lot of reading and read through most of the tutorials and documentation.

I've created a simple application and I'm stuck at a point where in a templa开发者_开发百科te, I want to be able to get fields from another model with the same parent. In this case I have a basic forum, with the model Post:

class Post(models.Model):
    ... 
    author = models.ForeignKey(User, related_name='forum_post_set')
    ...

Each post is assigned the User of whoever made the post. Then when displaying the posts in a thread, I am using the Django . template lookup to access fields from the User model:

{% for post in post_list %}
    ...
    Posted by {{ post.author.first_name }} {{ post.author.last_name }}
    ...
{% endfor %}

I then also have a Profile model which looks up to User as well:

class ZProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    extra_info = models.TextField(max_length=500, blank=True)

So my question is, how do I go about getting the field "extra_info" in my posts template using the author ("user") to reference to the user in the profile model. I have tried things like this:

{{ post.author.extra_info }}
{{ post.author.zprofile.extra_info }}
{{ post.author.user.zprofile.extra_info }}

etc etc.

Am I missing something here? I am obviously doing something wrong or missing a step, but I can't for the life of me find the answers I need in the documentation.

Any help is much appreciated!


Because ZProfile has a ForeignKey to User, you access it from User using .zprofile_set.0 (even though you specify unique=True). You'd be better off using a OneToOneField -- then you could use poll.author.zprofile.extra_info.

Django's auth app has support for user profiles which store additional information about users. If you use a OneToOneField, you can 'register' your ZProfile class using the AUTH_MODULE_PROFILE setting, then use post.author.get_profile.extra_info

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜