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">&nbsp&nbsp&nbsp&nbsp{{ 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

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -