How to use Django models ForeignKey? -
i used 2 foreignkey in table 'posts' connect table 'user', 1 username , icon, like:
user = models.foreignkey(userinfo, related_name='user_name') icon = models.foreignkey(userinfo, related_name='user_icon', null=true)
in views, try iterate table 'posts':
class allposts(view): def get(self, request): all_posts = posts.objects.all() return render(request, 'community.html', { "all_posts":all_posts, })
here's how iterate in template:
{% post in all_posts %} <div class="post"> <a href="" class="user_a"> <img class="icon" src="{{ media_url }}{{ post.icon }}"> <span class="name_span">{{ post.user }}</span> </a> <span class="time">发表时间:{{ post.add_time }}</span> <span class="clicked">回复:{{ post.comment_num }}</span> <a href=""> <img class="post_img" src="{{ media_url }}{{ post.image }}"> <div class="article"> <h3 class="title">{{ post.title }}</h3> <span class="content">    {{ post.content }}</span> </div> </a> </div> {% endfor %}
results:
<img class="icon" src="/media/none"> <span class="name_span">klawens</span>
so post.user show correct result, icon none, don't know how use foreignkey connect exact key want, , what's related_name exactly?
user field , icon field in 'posts' both point username in 'userinfo', want posts icon point userinfo icon, how that?
using {{ post.icon.icon }}
, {{ post.user.username }}
not {{ post.icon }}
or {{ post.user }}
Comments
Post a Comment