I need to select the objects to delete with a form on a webpage.
Since each object has a unique id, one way to select items to delete is using the id.
Following implements an example where a button on a webpage passes off the id of an object to delete which is processed in the view.py
file in a POST request.
views.py
from django.shortcuts import render
from .models import MyModel
def myview(request):
# initialize some data to delete
if request.method == 'GET': MyModel(name='John Doe', score=83).save()
# delete object with the id that was passed in the post request
if request.method == 'POST':
if 'delete' in request.POST:
try:
# id of the object to delete
key = request.POST['delete']
# delete that object
MyModel.objects.get(id=key).delete()
except MyModel.DoesNotExist:
pass
scores = MyModel.objects.all()
return render(request, 'mypage.html', {'scores': scores})
models.py
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=50)
score = models.IntegerField()
urls.py
from django.urls import path
from .views import myview
urlpatterns = [
path('mypage/', myview, name='mypage')
]
templates/mypage.html
<form method='post' action={% url 'mypage' %}>
{% csrf_token %}
{% for person in scores %}
{{ person.name }} {{ person.score }}
{% comment %} to differentiate entries, use id {% endcomment %}
<button name='delete', value="{{person.id}}">Delete</button><br>
{% endfor %}
</form>
It creates a webpage that looks like the following and when the Delete button is clicked, the entry for "John Doe" is deleted.