in model define thoughts , comments model. 1 thought has many comments so:
class thoughts(models.model): name = models.charfield(max_length=30) thought = models.charfield(max_length=500) class comments(models.model): name = models.charfield(max_length=30) comment = models.charfield(max_length=200) original_post = models.foreignkey(thoughts, default=0)
on site, when go view thought, want of comments appear. understanding can use choice_set access attributes via one-to-many relationship. here's view:
def thought(request, thought_num): if request.method == 'post': form = commentform(request.post) if form.is_valid(): c = comments.objects.create(name=form.cleaned_data['name'], comment=form.cleaned_data['comment']) c.save() else: form = commentform() get_post = thoughts.objects.get(pk=thought_num) comments = get_post.choice_set.all() return render(request, 'thought.html', {'form': form, 'comment':comments,})
in these lines, attempt access comments related particular thought in order print them in template.
get_post = thoughts.objects.get(pk=thought_num) comments = get_post.choice_set.all()
when access page should display comments, error:
exception type: attributeerror exception value:'thoughts' object has no attribute 'choice_set'
perhaps missing something, not sure. i'm sure it's simple. time
to retrieve comments related thought. can following:
thoughts.objects.get(pk=thought_num).comments_set.all()
if override default related_name ("comments_set"). can following: original_post = models.foreignkey(thoughts, default=0, related_name='choice_set')
Comments
Post a Comment