Django - How to allow only the owner of a new post to edit or delete the post?
<p>I will be really grateful if anyone can help to resolve the issue below.</p>
<p>I have the following Django project coding. The problem is: when the browser was given &quot;/posts/remove/&lt;post_id&gt;/&quot; or &quot;/posts/edit/(&lt;post_id&gt;/&quot; as the url, it will allow the second user (not owner) to perform the remove and edit jobs, respectively.</p>
<p>How can I allow only the owner of a new post to edit or delete the post?</p>
<p>account.models.py:</p>
<pre><code>from django.db import models
from django.conf import settings

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)

def __str__(self):
    return 'Profile for user {}'.format(self.user.username)
</code></pre>
<p>posts.models.py:</p>
<pre><code>from django.db import models
from django.conf import settings
from django.utils import timezone
from django.utils.text import slugify
from django.core.urlresolvers import reverse
from taggit.managers import TaggableManager

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager, self).get_queryset().filter(status='published')

class Post(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                         related_name='posts_created')
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique_for_date='created')
    image = models.ImageField(upload_to='images/%Y/%m/%d', null=True, blank=True)
    description = models.TextField(blank=True)
    created = models.DateTimeField(default=timezone.now,
                               db_index=True)
    updated = models.DateTimeField(auto_now=True)
    users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                    related_name='posts_voted',
                                    blank=True)

    status = models.CharField(max_length=10, default='published')

    objects = models.Manager() # The default manager.
    published = PublishedManager() # The Dahl-specific manager.                
                    
    tags = TaggableManager()

    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super(Post, self).save(*args, **kwargs)
    
    def get_absolute_url(self):
        return reverse('posts:detail', args=[self.id, self.slug])
</code></pre>
<p>posts.view.py:</p>
<pre><code>from django.views.decorators.http import require_POST
from django.shortcuts import render, redirect, get_object_or_404, render_to_response
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.conf import settings
from django.core.context_processors import csrf

from .forms import PostCreateForm, EmailPostForm, CommentForm, SearchForm
from .models import Post
from actions.utils import create_action

@login_required
def post_create(request):
    &quot;&quot;&quot;
    View for creating a new post.
    &quot;&quot;&quot;
    if request.method == 'POST':
        # form is sent
        form = PostCreateForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            cd = form.cleaned_data
            new_item = form.save(commit=False)
            # assign current user to the item
            new_item.user = request.user
            tags = form.cleaned_data['tags']
            new_item.save()
            for tag in tags:
                new_item.tags.add(tag)
            new_item.save()
            create_action(request.user, 'created a post:', new_item)
            messages.success(request, 'Post added successfully')
            form = PostCreateForm()
        else:
            messages.error(request, 'Error adding new post')

    else:
        # build form 
        form = PostCreateForm(data=request.GET)

    return render(request, 'posts/post/create.html', {'section': 'posts',
                                                    'form': form})


@login_required
def post_remove(request, post_id):
    Post.objects.filter(id=post_id).delete()
    return redirect('posts:mypost')

@login_required
def post_edit(request, post_id):
    item = Post.objects.get(pk=post_id)
    if request.method == 'POST':
        form = PostCreateForm(request.POST, instance=item)
        if form.is_valid():
            form.save()
            return redirect('posts:mypost')

    else:
        form = PostCreateForm(instance=item)

    args = {}
    args.update(csrf(request))
    args['form'] = form

    return render_to_response('posts/post/post_edit.html', args)
</code></pre>
<p>posts.urls.py</p>
<pre><code>from django.conf.urls import url
from . import views
from .feeds import LatestPostsFeed

urlpatterns = [
    url(r'^create/$', views.post_create, name='create'),
    url(r'^remove/(?P&lt;post_id&gt;\d+)/$', views.post_remove, name='post_remove'),
    url(r'^edit/(?P&lt;post_id&gt;\d+)/$', views.post_edit, name='post_edit'),
]
</code></pre>