0

I have a Comment Form for my django project, which has a two columns: Author, Text. I would like to make a author to be the currently looged user and be not able to edit that value. Is there a way to do it? Here are my codes

forms.py

class CommentForm(forms.ModelForm):
    author = forms.CharField(label = "名前", max_length=10,
        widget=forms.TextInput(attrs={'style': 'position: relative;left: 0px;'}))

    class Meta:
        model = Comment
        fields = ('author', 'text',)

views.py

def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('Post-detail', pk=post.pk)
    else:
        form = CommentForm()
    return render(request, 'blog/add_comment_to_post.html', {'form': form})

models.py

class Comment(models.Model):
    post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
    author = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    approved_comment = models.BooleanField(default=False)

    def approve(self):
        self.approved_comment = True
        self.save()

    def __str__(self):
        return self.text
  • Possible duplicate of [django form set current login user](https://stackoverflow.com/questions/4141408/django-form-set-current-login-user) – Lomtrur Jun 17 '19 at 07:25
  • Note that *you're already doing exactly what you need to* to set the Post automatically. Why can't you extend that to set the user? – Daniel Roseman Jun 17 '19 at 07:29
  • @Lomtrur that is not a good duplicate, it overcomplicates things. – Daniel Roseman Jun 17 '19 at 07:29
  • @Daniel Roseman so how could I show that `user` in html? Right now, I'm using a `{{ comment.author }}` –  Jun 17 '19 at 07:32
  • @Daniel Roseman how could I set a user? Where please? –  Jun 17 '19 at 07:33
  • 1
    Like I said, just like you did `comment.post = post` you can do `comment.author = request.user`. And remove `author` from the fields list, again like you removed `post`. – Daniel Roseman Jun 17 '19 at 07:42
  • @Daniel Roseman thank you! It went good –  Jun 17 '19 at 07:50

0 Answers0