在Django的主页中显示用户个人资料链接时出错

时间:2017-10-20 06:44:39

标签: python django django-templates

这是我的models.py

class Post(models.Model):
    topic = models.CharField(max_length=200)
    description = models.TextField()
    created_by = models.ForeignKey(User, related_name='posts')
    created_on = models.DateTimeField()

class Comment(models.Model):
    commented_by = models.ForeignKey(User, related_name='comments')
    commented_on = models.ForeignKey(Post, related_name='comments')
    commented_text = models.CharField(max_length=500)
    commented_time = models.DateTimeField(auto_now_add=True)

class Blogger(models.Model):
    username = models.OneToOneField(User, related_name='bloggers')
    blogger_bio = models.CharField(max_length=1000)

用户名

的URL.py
url(r'^(?P<username>[a-zA-Z0-9]+)/$', views.author_desc, name='author_desc'),

Views.py

from django.shortcuts import render, get_object_or_404
from .models import Post, User, Comment, Blogger
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def home(request):    
    posts_list = Post.objects.all()
    return render(request, 'home.html', {'posts': posts})

和我想要显示的home.html:

<!DOCTYPE html>
<html>
<head>
  <title>HOME</title>
</head>

<body>

<h2>All Blogs</h2>

{% for post in posts %}
  <a href="{% url 'post_desc' pk=post.pk %}"><b>Post Topic: </b>{{ post.topic }}</br></a>
      <b>Published Time: </b>{{ post.created_on }}</br>
      <b>Author: </b><a href="{% url 'author_desc' blogger.username %}">{{ post.created_by }}</a></br></br>
{% endfor %}

</body>

</html>

我想通过家中的链接显示每个博主的页面。但它正在遇到问题。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

检查blogger.username参数是否为空。

事实上,模型看起来并不那么好。 Post模型中的ForeignKey应该是Blogger模型。

class Post(models.Model):
    created_by = models.ForeignKey(Blogger, related_name='posts')

然后在模板中你可以做

{% for post in posts %}
 <a href="{% url 'post_desc' pk=post.pk %}"><b>Post Topic: </b>{{ post.topic }}</br></a>
  <b>Published Time: </b>{{ post.created_on }}</br>
  <b>Author: </b><a href="{% url 'author_desc' post.created_by.user.username %}">{{ post.created_by.user }}</a></br></br>{% endfor %}

答案 1 :(得分:0)

试试这个

{% for post in posts %}
<a href="{% url 'post_desc' pk=post.pk %}"><b>Post Topic: </b>{{ post.topic }}</br></a>
  <b>Published Time: </b>{{ post.created_on }}</br>
  <b>Author: </b><a href="{% url 'author_desc' post.created_by.username %}">{{ post.created_by }}</a></br></br>
{% endfor %}