Delete Objects Django.How

Author avatar wrote on 02/06/2022

View

Short

record = User.objects.get(id=request.POST['id'])
record.delete()

# or
User.objects.get(id=request.POST['id']).delete()

# With try
try:
    record = User.objects.get(id=request.POST['id'])
    record.delete()
except Exception as e:
    print("Exception Update balance ==========================")
    print(e)
    print("End of Exception  ==========================")


Multiple delete truncate

Category.objects.all().delete()
# or
Category.objects.filter(city="Paris").delete()

Delete Modal Template

Button - Make sure to change exception.id

Modal Make sure to change:

1.the form action url

2.the form name

JS

views.py

        elif request.POST.get("form_type") == 'delete_price_exception':
            try:
                record_to_delete = CompanyPriceException.objects.get(id=request.POST['id'])
                record_to_delete.delete()
                messages.success(request, "Record is successfully deleted." )
            except Exception as e:
                print("Exception delete_price_exception ==========================")
                messages.error(request, "Error. Something went wrong.")
                print(e)
                print("End of Exception  ==========================")
            return render(request, template_name, context)

End Delete Modal Template

CRUDgen Django CRUD generator