How to get value attribute in views

Hello is there a way to get 'value' attribute from HTML template into views.py and use it there?? HTML:

<form class="card__delete" method="POST"> {% csrf_token %}
                        <button value="{{item.id}}" class="card__delete__button"  name="delete" type="submit">&#10008</button>
                    </form> 

views.py

class TodoView(UserPassesTestMixin, CreateView):
   model = Item
   template_name = 'home/todo.html'
   form_class = ItemCreationForm
   def test_func(self):
       return self.request.user.username in self.request.path
   def get_context_data(self, **kwargs):
      context = super().get_context_data(**kwargs)
      context['card'] = Card.objects.get(user=self.request.user, pk=self.kwargs.get('pk'))
      return context
   def post(self, request, pk, username):
      if 'delete' in self.request.POST:
         Item.objects.get(id=pk).delete()
         print('deleted')
         return redirect('home-page')

The value is in request.POST, so you should be able to access it with

value = self.request.POST.get('delete', None)

Take care to validate that value before using the id of an object to do anything catastrophic to it (such as .delete()). It's not being validated through a form, and a random hacker on the internet might try posting back random numbers which might be the id of other objects

Added after reading comment (for some reason, clicking on add comment is just reloading the page for me 9th December 2021)

Data pulled out of request.POST is raw data. I don't think CSRF token can protect against a person who uses inspect object in his browser and changes the value of that button before clicking it. I may be wrong.

Anyway, if you can check the value using a queryset of the object type with a filter for objects that this user is permitted to delete, then do. For example,

value = request.POST.get("delete", None)
if value:
    obj = Whatever.objects.filter(
       user=request.user ).get( pk=value) 
    # will raise WhateverDoesNotExist if value isn't one of user's objects, 
    # becaues it's been filtered out
     obj.delete()

Something very screwy with StackOverflow at present. I can't see a preview of what I am typing.

Back to Top