There is a list generated in HTML, that represents all objects (Cards). There is already a delete button, but it's using Django functionality, and it requires a page to reload to take effect. Is there a simple way to include AJAX into the program?
I am a beginner to JavaScript and AJAX. I have tried some copy-paste solutions. I even tried to deconstruct a simple Django Ajax CRUD app, but it has too many functionalities, and it seemed like an overkill for my app (i would have to rewrite all the views, templates and urls). So I decided to ask a question over here with my own code.
views.py (List objects view)
def all_cards(request):
cards = Card.objects.all()
return render(request, 'all_cards.html', {'cards':cards})
all_cards.html
<body>
{% if cards %}
<table class="table" id="card-table">
<tr>
<th>Card owner name</th>
<th>Card balance</th>
</tr>
{% for card in cards %}
<tr>
<td>{{ card.cardholders_name }}</td>
<td>{{ card.card_balance }}€</td>
<td><form action="{% url 'card_delete' card.id %}" method="post">
{% csrf_token %}
<input type="submit" value='Delete'>
</form></td>
</tr>
{% endfor %}
{% else %}
<p>There are no cards registered.</p>
{% endif %}
</table>
</body>
urls.py
url(r'(?P<id>\d+)/$', views.card_delete, name='card_delete'),
views.py (Delete object view)
def card_delete(request, id):
card_that_is_ready_to_be_deleted = get_object_or_404(Card, id=id)
if request.method == 'POST':
card_that_is_ready_to_be_deleted.delete()
return HttpResponseRedirect('/all_cards')
As you can see, the form's input(
<input type="submit" value='Delete'>
)calls Django's view via URL.
I expect the delete button to call an AJAX functionality, that will do a similar thing.
How should I go about writing that functionality?
P.S.: This is my first StackOVerflow question, I'm open for constructive criticism.
def card_delete(request, id):is calling when you press button or not.for this you can addingprint("I am in view")to above of code in card_delete function.