2014-03-19 51 views
1

我已经使我网站上的用户可以上传帖子,并查看来自其他用户的所有其他帖子。下面的代码附加了编写帖子userpicture的用户。使用户图片成为链接

我希望它成为该用户的链接。我的问题是,下面的代码链接到当前用户,而不是创建帖子的用户。

任何人有一些想法如何解决这个问题?谢谢!

{% if item.sender.userpicture_set.all %} 
     {% for item in item.sender.userpicture_set.all %} 
      {% if item.active %} 
       {% if forloop.first %} 
        {% if forloop.last %} 
         <a href='/members/{{ user.username }}'><img src='{{ MEDIA_URL }}{{ item.image }}' class='img-responsive' id='post-userpicture'/></a> 
        {% endif %} 
       {% endif %} 
      {% endif %} 
     {% endfor %} 
      <small><a href='/members/{{ user.username }}'>{{ item.sender }}</a><span style='color: grey;'> {{ item.sent }}</span></small> 
{% endif %} 
+0

在您的模型中,如果您已将用户的外键字段添加到帖子(上载的)模型中,则可以使用上下文在视图中检索用户。你可能需要你的模型和视图来帮助你更多。 – abrunet

回答

0

在你item模型中,添加一个字段username,它存储了username of the user who made this post

在此,它创建一个指向当前用户的链接,因为“用户”没有任何关于帖子的信息。它有关于当前用户的信息。

添加 '用户名' 字段后,

{% if item.sender.userpicture_set.all %} 
     {% for item in item.sender.userpicture_set.all %} 
      {% if item.active %} 
       {% if forloop.first %} 
        {% if forloop.last %} 
          <a href='/members/{{ item.sender.username }}'><img src='{{ MEDIA_URL }}{{ item.image }}' class='img-responsive' id='post-userpicture'/></a> 
        {% endif %} 
       {% endif %} 
      {% endif %} 
     {% endfor %} 
      <small><a href='/members/{{ item.sender.username }}'>{{ item.sender }}</a><span style='color: grey;'> {{ item.sent }}</span></small> 
{% endif %} 

UPDATE:

我不得不改变item.sender.username。这应该工作。

+0

这是我的发帖模型: class Posts(models.Model): post = models.CharField(max_length = 3000) sender = models.ForeignKey(User,related_name ='sent_the_post',null = True,blank = True) sent = models.DateTimeField(auto_now_add = False,auto_now = False,null = True,blank = True) read = models.DateTimeField(auto_now_add = False,auto_now = False,null = True,blank = True) timestamp = models .DateTimeField(auto_now = False,auto_now_add = True) 您将如何创建该字段用户名,该字段用于存储上述内容? – Christo

+0

上面有点杂乱,但有邮件,发件人,发送,阅读和时间戳。 – Christo

+0

我做了更改。请检查。 –

0

的问题是,您要引用您的链接user对象<a href='/members/{{ user.username }}'>,正确的URL应该像<a href='/members/{{ item.sender.username }}'>但它需要你有一个ForeignKey参考的项目模型的用户。

+0

我有一个外键:sender = models.ForeignKey(User,related_name ='sent_the_post',null = True,blank = True) - 我试过了: 但它不起作用:( – Christo