Dannad
Dannad

Reputation: 189

How can I implement that only the author of a post can see the delete button (Django-Templates)

How can I implement that only the author of the post can even see the "delete-button" and the "edit-button"?

Currently my template looks like this:

{% if user.is_authenticated %}
    <hr>
        <a href="{% url 'blog:delete_post' pk=post.pk %}">Delete |</a>
        <a href="{% url 'blog:post_update' pk=post.pk %}">Edit</a>
{% endif %}

I found an example, where they used

{% if user.is_authenticated and post.author == request.user%}

but then even the author of the post could not see the two buttons. All the other stuff in my tempate is defined like {{ post.author }}, {{post.title }} and so on.

My class post has a foreignkey author (from user). And even if you can see the button only the actual author can delete the post, so the views are all working. The only thing I am struggeling with is the template. I would be glad for any help!

These are my context_processors in settings.py:

'context_processors': [
            'django.contrib.auth.context_processors.auth',
            'django.template.context_processors.debug',
            'django.template.context_processors.i18n',
            'django.template.context_processors.media',
            'django.template.context_processors.static',
            'django.template.context_processors.tz',
            'django.contrib.messages.context_processors.messages'
]

And these are my models for Post and UserProfile:

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    title = models.CharField(max_length=200)
    content = models.TextField()

class UserProfile(models.Model):
    user = models.OneToOneField(User)

Upvotes: 1

Views: 597

Answers (1)

Gustavo Carvalho
Gustavo Carvalho

Reputation: 178

Try comparing the primary keys:

{% if post.author.pk == request.user.pk %}...{% endif %}

Upvotes: 1

Related Questions