В
models.py username поменяйте на
ForeignKey
from django.contrib.auth.models import User
class Comments(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Пользователь')
text_comments = models.TextField('Текст комментария', max_length=200)
post = models.ForeignKey(Post, verbose_name='Публикация', on_delete=models.CASCADE)
def __str__(self):
return f'{self.user.username} / {self.post}'
В
form.py исключите name
class CommentsForm(forms.ModelForm):
class Meta:
model = Comments
fields = ('text_comments',)
В
views.py добавьте поле user
class AddComments(View):
def post(self, request, post_id):
form = CommentsForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post_id = post_id
comment.user = request.user
comment.save()
return redirect('post_detail', post_id=post_id)
В
post_detail.html добавьте user.username
<div>
<h3>Комментарии:</h3>
<form action="{% url 'add_comments' post.id %}" method="post">
<h3></h3>
{% csrf_token %}
<div>
<textarea name="text_comments" placeholder="Ваш комментарий..."></textarea>
</div>
<div><input type="submit"></div>
</form>
</div>
<div>
{% for comment in post.comments_set.all reversed %}
<div class="view-comment">
<h4>{{ comment.user.username }}</h4>
<p><i>{{ comment.text_comments }}</i></p>
</div>
{% endfor %}
</div>
Должно работать