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