如何用当前页面的值填充表单?

2024-09-25 16:33:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习在Django上建立一个评论后应用程序。我理解如何以及为什么可以在评论表单中将当前用户指定为作者。但我不明白如何分配post\u id来连接评论和特定的post

尝试使用从网上搜索得到的各种方法。我不断地遇到各种各样的错误——TypeError、KeyError、ValueError等等

My models.py的设置如下:

class Post(models.Model):
    pid = models.AutoField(primary_key=True)
    title = models.CharField(max_length=1000)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('blog-home')#, kwargs={'pk':self.pk})


class Comment(models.Model):
    cid = models.AutoField(primary_key=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    comment = models.TextField()
    comment_date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.comment


    def get_absolute_url(self):
        return reverse('blog-home')

    def save(self, *args, **kwargs):
        super(Comment, self).save(*args, **kwargs)

带有comment create视图的views.py如下所示:

class CommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    fields = ['comment']

    def form_valid(self, form,**kwargs):
        form.instance.author = self.request.user
        form.instance.post_id = self.kwargs['post_id']
            # IS THE ABOVE LINE CORRECT?
        return super().form_valid(form)

答案按钮在主页上,包含在每个帖子块中。其html及其url如下:

{% extends "blog/base.html" %} {% block content%} {% for post in posts%} <article class="media content-section"> <img class="rounded-circle article-img" src="{{post.author.profile.image.url}}"> <div class="media-body mb-8"> <div class="article-metadata mb-4"> <a class="mr-4" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y P e" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.pid %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> <div class="border border-top-0"> <a class="btn float-right btn-info mb-0 mt-1" href="{% url 'comment-create' post.pid %}">Answer</a> $$$$$ HERE IS THE URL FOR THE ANSWER BUTTON $$$$ </div> </div> </article> {% endfor %} {% endblock %}

我不知道如何传递post\u id或用户单击的post的id。请帮忙


Tags: selfdivformidurlreturntitlemodels