(DJANGO)如何在作者评论区中设置current.username

时间:2020-03-07 18:11:09

标签: django django-models

我的Django应用中有HEAD模型。

我想使评论作者成为当前注册的Comment,而不是另一个注册帐户。

这是屏幕截图,我可以选择author帐户来发表评论,但目前我是user2帐户。enter image description here

这是我的Django user1模型:

Comment

以及来自html表单的一些代码:

class Comment(models.Model):
    post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
    name = models.ForeignKey(User, on_delete=models.CASCADE)
    email = models.EmailField()
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=False)

    class Meta:
        ordering = ['created_on']

    def __str__(self):
        return 'Comment {} by {}'.format(self.body, self.name)

编辑

view.py

  <article class="media content-section">
    <div class="media-body">
      <!-- comments -->
      {% if comments.count == 1 %}
        <h2>{{ comments.count }} comment</h2>
      {% else %}
        <h2>{{ comments.count }} comments</h2>
      {% endif %}

      {% for comment in comments %}
      <div class="comments" style="padding: 10px;">
        <p class="font-weight-bold">
          {{ comment.name }}
          <span class=" text-muted font-weight-normal">
            {{ comment.created_on }}
          </span>
        </p>
        {{ comment.body | linebreaks }}
      </div>
      {% endfor %}
      {% if new_comment %}
      <div class="alert alert-success" role="alert">
        Your comment is awaiting moderation
      </div>
      {% else %}
      <h3>Leave a comment</h3>
      {% load crispy_forms_tags %}
      <form method="post" style="margin-top: 1.3em;">
        {{ comment_form | crispy }}
        {% csrf_token %}
        <button type="submit" class="btn btn-primary  btn-lg">Submit</button>
      </form>
      {% endif %}
    </div>
  </article>

2 个答案:

答案 0 :(得分:3)

通过将editable=… parameter [Django-doc]设置为False,可以使该字段不可编辑。我进一步建议使用user not name,因为它是对用户对象的引用,而不是用户名:

class Comment(models.Model):
    post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
    user = models.ForeignKey(User, editable=False, on_delete=models.CASCADE)
    email = models.EmailField()
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=False)

    class Meta:
        ordering = ['created_on']

    def __str__(self):
        return 'Comment {} by {}'.format(self.body, self.user)

然后,在您认为有效的表单中,将表单的instance.user设置为request.user

from django.contrib.auth.decorators import login_required

@login_required
def add_comment(request, post_id):
    # …
    if request.method == 'POST':
        form = CommentForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.user = request.user
            # …
        # …
    # …

答案 1 :(得分:1)

好吧,应该没有用户的选择。要识别用户,只需在视图中使用request.user。我不知道您的视图如何,但是您可以像这样设置name

name = request.user
# or if you're using classes:
name = self.request.user