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

2024/10/10 18:20:04

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 settingsclass 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 TaggableManagerclass 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.titledef 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 csrffrom .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 sentform = PostCreateForm(data=request.POST, files=request.FILES)if form.is_valid():cd = form.cleaned_datanew_item = form.save(commit=False)# assign current user to the itemnew_item.user = request.usertags = 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'] = formreturn render_to_response('posts/post/post_edit.html', args)

posts.urls.py

from django.conf.urls import url
from . import views
from .feeds import LatestPostsFeedurlpatterns = [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'),
]
Answer

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
https://en.xdnf.cn/q/69864.html

Related Q&A

Py4J has bigger overhead than Jython and JPype

After searching for an option to run Java code from Django application(python), I found out that Py4J is the best option for me. I tried Jython, JPype and Python subprocess and each of them have certai…

how to uninstall opencv-python package installed by using pip in anaconda?

I have tried to install OpenCV in anaconda. but when I use it, I figure out the instead of using OpenCV, the program using OpenCV-python and that why my program crashed. I type "conda uninstall op…

flask many to many join as done by prefetch_related from django

I have following Group and Contact model in flask with Sql Alchemy ORMgroup_contact = db.Table(group_contact,db.Column(group_id, db.Integer, db.ForeignKey(group.id)),db.Column(contact_id, db.Integer, d…

Django model inheritance - only want instances of parent class in a query

Lets say I have 2 models, one being the parent of another. How can I query all Places that arent restaurants in Django? Place.objects.all() would include all restaurants right? I want to exclude the …

Perfom python unit tests via a web interface

Is it possible to perform unittest tests via a web interface...and if so how?EDIT: For now I want the results...for the tests I want them to be automated...possibly every time I make a change to the …

Limit on number of HDF5 Datasets

Using h5py to create a hdf5-file with many datasets, I encounter a massive Speed drop after ca. 2,88 mio datasets. What is the reason for this?I assume that the limit of the tree structure for the dat…

Object level cascading permission in Django

Projects such as Django-guardian and django-permissions enables you to have object level permissions. However, if two objects are related to each other by a parent-child relationship, is there any way …

How do I find out eigenvectors corresponding to a particular eigenvalue of a matrix?

How do I find out eigenvectors corresponding to a particular eigenvalue? I have a stochastic matrix(P), one of the eigenvalues of which is 1. I need to find the eigenvector corresponding to the eigen…

How to install my custom Python package with its custom dependencies?

I would like to find a way to install my own python package which depends on other custom python packages. I followed this guide to create my own python packages: https://python-packaging.readthedocs.i…

How to call a function only Once in Python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 8 years ago.The com…