Anton Anton - 3 years ago 172
Python Question

Why django do not display comments?

my model :

class Post(models.Model):
message = models.TextField(max_length=4000)
topic = models.ForeignKey(Topic, related_name='posts')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(null=True)
created_by = models.ForeignKey(User, related_name='posts')
updated_by = models.ForeignKey(User, null=True, related_name='+')

class Comments(models.Model):
creator = models.ForeignKey(User, related_name='comment')
body = models.TextField(max_length=4000)
post = models.ForeignKey(Post, related_name='comment', null=True)

my view:

def p(request, pk):
topic = get_object_or_404(Topic, pk=pk)
post = get_object_or_404(Post, pk=pk)
return render(request, 'post.html', {'post': post, 'topic': topic})

def comments(request, pk):
comment = get_object_or_404(Comments, pk=pk)
return render(request, 'post.html', {'comment': comment})

my urls:

url(r'^boards/(\d+)/(?P<pk>\d+)$', views.p, name='p'),
url(r'^boards/(\d+)/(\d+)/$', views.comments, name='comments'),

as i can understand, the problem in using primary key, in case of posts all work good, but when i try to render different models in one page it looks like that django go not like it. I tryed a lot of combinations in url pattern, but nothing that solved my problem. On post.html page all info about posts redered as well, but comments is not work. Important that i want display comments on same url with post

Answer Source

Your fundamental misconception is that you need two views (and therefore two URLs). You don't. You need to assemble the entire response and return it from a single view.

One possibility is to do this in the view itself. However, since the comments are related to the post, the easiest thing is just to follow the relationship in the template:

{{ post.message }}
{% for comment in post.comment.all %}
  {{ comment.body }}
{% endfor %}

(Note, you have explicitly set your reverse relation to be comment, by setting related_name. This makes no sense, because there are many comments. Really you should not define a related name unless you have a really good reason, which you don't here; the default, comment_set, is perfectly valid and makes more sense.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download