Django model association, users, profiles and idea model
I have an app that makes use of 'django-registration' a custom built model named 'idea' and also a 'userprofile'
Now the Idea class looks as follows
class Idea(models.Model):
开发者_如何学JAVA title = ... user = models.ForeignKey(User)
The User class is Django's Auth User system.
And the UserProfile looks as follow.
class UserProfile(ImageModel):
user = models.ForeignKey(User) image = models.ImageField(.....)
Now lets say in my frontpage I want to display all Idea and have the user and his "avatar" to display.
How do I associate all three models without having to render it through the Context.
{% for ideas in idea %}
{{ idea.user.get_full_name }} just posted an idea with the name of {{ idea.title }} {% endofr %}
Now I would like to display the users profile pic in this too.
Best I can come up with is
{% for userprofile in idea.user_set.all %}
img src="{{ userprofile.image }}" {% endfor %}
The idea instance has a user, by way of the ForeignKey. On user instances, you have a get_profile
method that returns the related profile for this user.
So you could do something like this (untested):
{% for idea in ideas %}
{{ idea.user.get_full_name }} <img src="{{ idea.user.get_profile.image }}"/> just posted an idea with the name {{ idea.title }}
{% endfor %}
I think the easiest way in the long run is to register an inclusion tag so you can reuse this with any model.
精彩评论