Как вывести название поста на странице new_comment - PullRequest
0 голосов
/ 12 мая 2019

Я хотел бы знать, как я могу отобразить название сообщения на моей странице comment_new:

views.py

def comment_new(request, pk):
    if request.method == "POST":
        form = CommentForm(request.POST)
        post = get_object_or_404(Post, pk=pk)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.published_date = timezone.now()
            comment.post = post
            comment.save()
            messages.success(request, 'You have successfully provided a comment for this Post.')
            return redirect('post_detail', pk=comment.post.pk)
        else:
            form = CommentForm(request.POST)
            return render(request, 'app/comment_new.html', {'form': form})
    else:
        form = CommentForm()
        return render(request, 'app/comment_new.html', {'form': form})

models.py

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(verbose_name="Post Title", max_length=40)
    content = models.TextField(verbose_name="Post Content", max_length=5000)
    tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True)
    category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)

template.html

<a>{{ post.title }}</a>

дан атрибут заголовка.Я понятия не имею, почему это не работает.

спасибо заранее

1 Ответ

0 голосов
/ 13 мая 2019

Я предполагаю, что вы хотите отобразить заголовок сообщения, когда пользователь собирается добавить новый комментарий.Я имею в виду, когда запрос GET (отобразить форму нового сообщения).

def comment_new(request, pk):

    # This line is better here since you'll be working with
    # the post instance no matter the request method is POST or GET.
    post = get_object_or_404(Post, pk=pk)

    if request.method == "POST":
        # ...
    else:
        form = CommentForm()
        # And here pass post as part of the context to your template.
        return render(request, 'app/comment_new.html', {'form': form, 'post': post})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...