user10634359
user10634359

Reputation:

In a django app, how do I prevent users from deleting content not created by them?

I have created a simple question apps, when clicked on questions it shows its options or choices.I made login and signup forms to make user-login.

I want to know how can I limit the user to delete the questions created only by them.Every question has a delete key infront of it.

I read most stuff about permissions but didnt got it how to do it.

I may apply permission not to delete any question but how to restrict a user not to delete only some specific questions or questions that weren't created by them. below is views.py

def addquestion(request):
    item_to_add = request.POST['content']
    item = Question.objects.create(question_text=item_to_add,pub_date=timezone.now())
    user_now = Question(user = request.user)
    item.save()

    return HttpResponseRedirect('/home/questions')


def deletequestion(request,question_id):

    item_to_delete = Question.objects.get(id=question_id)
    if item_to_delete.user == request.user:
        item_to_delete.delete()
    else:
    return HttpResponse('You are not authorised to delete this question')

Here is models .py

from django.db import models
from vote.models import VoteModel
from django.contrib.auth.models import User

# Create your models here.
class Question(VoteModel,models.Model):

    question_text = models.TextField(max_length=300)
    pub_date = models.DateTimeField('date published')
    user = models.OneToOneField(User,on_delete = models.CASCADE,null=True)

    def __str__(self):
        return self.question_text

class Choice(models.Model):
    choice_text = models.CharField(max_length=300)
    votes = models.IntegerField(default=0)
    question = models.ForeignKey(Question,on_delete = models.CASCADE)

    def __str__(self):
        return self.choice_text

Upvotes: 2

Views: 984

Answers (2)

You should filter your questions queryset:

from django.db.models import Q
...
try:
    Question.objects.get(Q(id=question_id)&Q(user=request.user)).delete()
except Question.DoesNotExist:
    raise PermissionDenied("User can't delete this question.")
...

The Q object allows you to logically operate with filters.

Reference: https://docs.djangoproject.com/es/2.1/topics/db/queries/#complex-lookups-with-q-objects

Update: As pointed out in comments, in this particular case you can achieve this by doing the following:

try:
    Question.objects.get(id=question_id, user=request.user).delete()
except Question.DoesNotExist:
    raise PermissionDenied("User can't delete this question.")

Upvotes: 4

Amine Messaoudi
Amine Messaoudi

Reputation: 2299

Maybe request.user is a string that contains the id of the user so you will have to get the user object of that id before comparing it with item_to_dele.user.

logged_user = User.objects.get(id=request.user)
if logged_user == item_to_delete.user:
    # delete
    item_to_delete.delete()
else:
    return HttpResponse('You are not authorised to delete this question')

Upvotes: 0

Related Questions