Django delete an object
Good day, I have a Model object, which contains the user who created it, as well as the one specified in a form.
with localhost:800/delete/int:title_id/ the one object is deleted.
Question: How can I make sure that user a user who also created the object can delete it.
If userXY owns the object with ID 123 and he calls localhost:800/delete/123, the object will be deleted.
But if OtherNutzerYX calls localhost:800/delete/123, the object will not be deleted because the object does not belong to him, but to UserXY.
models.py
class NewTitle(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
default=None,
null=True,
on_delete=models.CASCADE,
)
title = models.CharField(max_length=200)
creator_adress = models.GenericIPAddressField(null=True)
id = models.BigAutoField(primary_key=True)
def __str__(self):
return str(self.title)
urls.py
path('delete/<int:title_id>/', views.title_delete),
views.py
def title_view(request):
titles = NewTitle.objects.all()
custom_title_id = random.randint(1111, 1111111111111)
if request.method == 'POST':
form = NewTitleForm(request.POST, instance=NewTitle(user=request.user))
if form.is_valid():
obj = form.save(commit=False)
obj.creator_adress = get_client_ip(request)
obj.id = custom_title_id
while NewTitle.objects.filter(id=obj.id).exists():
obj.id = random.randint(111, 11111111111)
obj.save()
return redirect('/another')
else:
form = NewTitleForm()
return render(request, 'test.html', {'form': form, 'titles': titles})
def title_delete(request, title_id):
if #WHAT CODE HERE?:
NewTitle.objects.filter(id=title_id).delete()
else:
return redirect('https://example.com')
return HttpResponseRedirect('/another')
The relevant code is the title_delete function. I don't know what to write in the if statement. It has something to be like: 'if user of the title id == the user who is requesting the url == delete the model' 'else = if the user is not the owner, go to example.com and do not delte the model'
We can get the user who requested the url with request.user now we just need to check if the request.user is equal to the owner of the model. How?
(By the way, if there are better ways to create a custom ID for each model or you notice something else about my code that could be better, please tell me)
Thanks for your help :-)
Solution 1:
As you have mentioned you only want to delete the title object if the object is created by a currently logged-in user.
Here is how you can achieve it
def title_delete(request, title_id):
user_title = NewTitle.objects.filter(id=title_id,
user=request.user)
if user_title:
user_title.delete()
else:
return redirect('https://example.com')
return HttpResponseRedirect('/another')
you can also call .first()
after filter if you are sure that your user base only one title
user_title = NewTitle.objects.filter(id=title_id,
user=request.user).first()