我刚刚在用Django构建的社交网络应用程序上创建了一个用户评论系统(python版本2.7.8,Django版本1.6)。
评论系统一切运作良好,但我遇到了一个问题。如果用户在其中一条评论中提交指向外部网站的链接,则该链接将显示为纯文本。我希望用户提交的链接自动被视为其他用户可以点击的链接。
有谁知道这个问题的潜在解决方案?
models.py
class Comment(models.Model):
#Model that defines the Commenting system
created = models.DateTimeField(editable =False)
author = models.CharField(max_length = 200, editable = False)
body = models.TextField()
item = models.ForeignKey(BucketListItem)
def __unicode__(self):
return self.body
评论-template.html
<h2>Comments:</h2>
<br>
{% if comments %}
{% for comment in comments %}
<div class = "comment-div">
<h5>{% avatar comment.author 40 %}</h5>
<h5><a href = "/bucketlist/userstats/{{comment.author}}/"> {{comment.author}}</a></h5>
<h5 class ="timesince">{{ comment.created|timesince}} ago.</h3>
<br>
<br>
<p>{{comment.body}}</p>
{% if comment.author == current_user %}
<a href="/bucketlist/item/{{comment.id}}/delete-comment/"><span class = "fa fa-close"></span></a>
{% endif %}
</div>
{% endfor %}
<br>
<hr>
<br>
{% else %}
<p>There are no comments yet. Be the first to add one!</p>
{% endif %}
<h5 class = "leave-comment">Leave a Comment Here: </h5>
<br>
<form action="/bucketlist/item/{{id}}/" method = "post" role = "form">
<div class = "form-group">
{% csrf_token %}
{% for field in form %}
{{ field.errors }}
{{ field }}
<br>
{% endfor %}
<br>
<input type = "submit" value = "Submit" class="btn btn-warning">
</div>
<br>
答案 0 :(得分:9)
您应该可以使用Django提供的the urlize
template tag来执行此操作。
<p>{{ comment.body | urlize }}</p>
这应该将评论正文中的任何链接转换为实际的<a>
代码。