This is my 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 for username
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})
and my home.html where i want to display:
<!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>
I want to show each blogger's page from a link from the home. But it is getting problem.
What i'm doing wrong here?
Check whether blogger.username
parameter is empty.
Infact the models are not looking that good. The ForeignKey in the Post model should be to the Blogger
model.
class Post(models.Model):
created_by = models.ForeignKey(Blogger, related_name='posts')
Then in the template you can do
{% 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 %}
Try this
{% 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 %}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.