I am fairly new to Django, and I got some feedback for my project (recipe app) that I am currently working on from my mentor about defensive programming. I have created a delete "function" in my app views in Django, and he told me to remake the function so no one else than the author of the recipe could ever delete the selected recipe. I have included authentication for this in my HTML but he told me to do the same for my delete view. Does anyone have a good explanation for how I could achieve this in a simple way?
I have never before asked a question here so give me feedback if I have provided the right information for a question like this.
Here is my delete view today:
def delete_recipe(request, slug):
"""
View for delete recipe
"""
recipe = Recipe.objects.get(slug=slug)
recipe.delete()
return redirect('home')
I know the best Description, how you can do it. It is here: https://docs.djangoproject.com/en/4.0/topics/auth/default/#django.contrib.auth.decorators.permission_required
For best practice, you should check if user has
object_delete_permission.But it is not all:
After that you should check if this is author of product:
For me is not clear, why you dont do it with Django-GCBV
DeleteView. https://docs.djangoproject.com/en/4.0/ref/class-based-views/generic-editing/#deleteviewThis view give you all, that you need, in box.
And, of Course, try to delete something only on POST or DELETE.