Я не могу запросить имя пользователя и не могу сравнить с автором. он работал для одного случая, который опубликован ниже.
{% if user.is_authenticated %}
{% if user.get_username == blog.author %}
<a href="{% url 'update' pk=blog.pk %}"><i class="fas fa-pen fa-2x fa-spin"></i></a>
{% endif %}
{% if user.is_superuser %}
<a href="{% url 'update' pk=blog.pk %}"><i class="fas fa-pen fa-2x fa-spin"></i></a>/
<a href="{% url 'delete' pk=blog.pk %}"><i class="fas fa-trash-alt fa-2x fa-spin"></i></a>
{% endif %}
{% endif %}
мой взгляд
@login_required(login_url='login')
def update_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == 'POST':
form = EditPost(request.POST, request.FILES, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.last_edited = timezone.now()
post.save()
return redirect('blog', pk=post.pk)
else:
form = EditPost(instance=post)
context = {'form': form}
return render(request, 'blog/edit_post.html', context)
моя модель
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200, null=True)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
pub_date = models.DateTimeField(blank=True, null=True)
last_edited = models.DateTimeField(null=True, blank=True)
def __str__(self):
return f'{self.title} by author {self.author}'
, но он работал для
{% for comment in blog.comments.all %}
<cite>{{ comment.author }}</cite>
<time class="comment__time">{{ comment.created_date }}</time>
{% if user.is_authenticated and request.user.username == comment.author %}
<a class="reply" href="{% url 'remove' pk=comment.pk %}">remove</a>
{% endif %}
<div class="comment__text">
<p>{{ comment.comment }}</p>
{% endfor %}
для этой модели
class Comment(models.Model):
post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=50, null=True)
comment = models.TextField()....
def __str__(self):
return f'{self.comment} by user {self.author}'