Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How to allow only the owner of a new post to edit or delete the post?

Tags:

python

django

I will be really grateful if anyone can help to resolve the issue below.

I have the following Django project coding. The problem is: when the browser was given "/posts/remove/<post_id>/" or "/posts/edit/(<post_id>/" as the url, it will allow the second user (not owner) to perform the remove and edit jobs, respectively.

How can I allow only the owner of a new post to edit or delete the post?

account.models.py:

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)

posts.models.py:

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])

posts.view.py:

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):
    """
    View for creating a new post.
    """
    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)

posts.urls.py

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<post_id>\d+)/$', views.post_remove, name='post_remove'),
    url(r'^edit/(?P<post_id>\d+)/$', views.post_edit, name='post_edit'),
]
like image 853
hongkail Avatar asked Nov 09 '16 12:11

hongkail


People also ask

What does _() mean in Django?

_ in Django is a convention that is used for localizing texts. It is an alias for ugettext_lazy.

How do I delete a record in Django?

To delete a record we do not need a new template, but we need to make some changes to the members template. Of course, you can chose how you want to add a delete button, but in this example, we will add a "delete" link for each record in a new table column. The "delete" link will also contain the ID of each record.


1 Answers

Add request.user == item.user check inside your method.

@login_required
def post_remove(request, post_id):
   item = Post.objects.get(pk=post_id)
   if request.user == item.user:
      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.user == item.user:
      ...
      //write your code here
like image 165
Satendra Avatar answered Nov 09 '22 17:11

Satendra