In a template of my project, I am using a for
loop to iterate over each object in a model. Each object needs a button next to it that will delete THAT object from the model. So each button needs to be linked to a specific object, and clicking that button will tell views.py which object has been licked and to delete that object.
models.py:
class Obj(models.Model):
name = models.Charfield(max_length=255)
template.html:
{% for object in objects %}
{{object.name}}<br>
<form method="post" action=".">
<button type="submit">Select</button>
</form>
{% endfor %}
views.py:
def delete(request):
objects = Obj.objects.all()
if request.method == 'POST':
# Get the specific object that the form was submitted for
# Remove the object from the model (which removes it from the html list as well)
return render(request, 'template.html', {'objects', objects})
CodePudding user response:
You need to send the id of your object alongside your request. So you add the object id in your form:
{% for object in objects %}
{{object.name}}<br>
<form method="post" action=".">
{% csrf_token %} {# Don't forget this one ! #}
<button type="submit" name="object-id" value="{{ object.pk }}">Select</button>
</form>
{% endfor %}
You then delete the object from your view:
from django.http import Http404, HttpResponseNotAllowed
def delete(request):
if request.method == 'POST':
try:
obj = Object.objects.get(pk=request.POST.get('object-id')
except Object.DoesNotExist:
raise Http404()
obj.delete()
return reverse('...')
return HttpResponseNotAllowed()