Scott K.
Scott K.

Reputation: 311

Create a vanilla JavaScript confirm delete modal when deleting a Django object

Most answers for this on Stack Overflow are written using Ajax and or jQuery. For an assignment I need it to be vanilla JS. This is what I have so far. Strangely I have a working delete button with a GET request method. Not a POST method as it normally would be. I'm not sure why and honestly got it working without the confirmation modal with trial and error.

This is what I have so far:

urls.py

from django.urls import path
from . import views


urlpatterns = [
    path('', views.home, name='vgHome'),  # relative path to VideoGames homepage
    path('about/', views.about, name='vgAbout'),  # relative path to VideoGames about page
    path('news/', views.news, name='vgNews'),  # realtive path to VideoGames news page
    path('gallery', views.gallery, name='vgGallery'),  # relative path to VideoGames gallery page
    path('library/', views.library, name='vgLibrary'),  # relative path to VideoGames user library
    path('library/create', views.create_game, name='addGame'),  # realative path to game create form
    path('library/<int:game_id>/game_info', views.game_info, name='gameInfo'),  # realative path to each games info page
    path('library/<int:game_id>/update', views.update_game, name='updateGame'),  # relative path to update selected game
    path('library/<int:id>/delete', views.delete_game, name='deleteGame'),  # relative path to delete selected game
]

views.py

from django.shortcuts import render, get_object_or_404, HttpResponseRedirect, redirect
from django.contrib import messages
from .forms import GameForm
from .models import Game


# Displays VideoGames app homepage
def home(request):
    return render(request, 'VideoGames/videogames_home.html')


# Displays VideoGames about page
def about(request):
    return render(request, 'VideoGames/videogames_about.html')


# Displays VideoGames news page
def news(request):
    return render(request, 'VideoGames/videogames_news.html')


#  Displays VideoGames gallery page
def gallery(request):
    return render(request, 'VideoGames/videogames_news.html')


# Displays VideoGames user library page
def library(request):
    games_list = Game.objects.all()
    context = {
        'games_list': games_list,
    }
    return render(request, 'VideoGames/videogames_library.html', context)


# Displays each games details page, linked from library
def game_info(request, game_id):
    game = get_object_or_404(Game, pk=game_id)
    return render(request, 'VideoGames/game_details.html', {'game': game})


def create_game(request):
    if request.method == 'POST':
        form = GameForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'Game successfully added!')
            return redirect('vgLibrary')
        else:
            messages.error(request, 'Please fix fields with errors!')
    else:
        form = GameForm()
    return render(request, 'VideoGames/game_form.html', {'form': form})


def update_game(request, game_id):
    game = get_object_or_404(Game, pk=game_id)
    form = GameForm(request.POST or None, instance=game)
    context = {'form': form}
    if form.is_valid():
        form.save(commit=False)
        form.save()
        messages.success(request, 'Game successfully updated!')
        return redirect('vgLibrary')
    return render(request, 'VideoGames/game_update.html', context)


def delete_game(request, id=None):
    game = get_object_or_404(Game, id=id)
    if request.method == 'GET':
        game.delete()
        messages.success(request, 'Game successfully deleted!')
        return redirect('vgLibrary')
    else:
        return render(request, 'VideoGames/game_details.html', {'game': game})

Template where delete button is located (game_details.html)

{% extends 'VideoGames/videogames_base.html' %}
{% load staticfiles %}

{# Page/Tab Title #}
{% block title %}Video Games | Library | {{ game.game_title }}{% endblock %}

{# Using parent stylesheet + adding page specific css file as well #}
{% block stylesheets %}
    {{ block.super }}
    <link rel="stylesheet" type="text/css" href="{% static 'VideoGames/css/vg_details.css' %}">
{% endblock %}

{# Homepage background image #}
{% block pagetop-css %}{% endblock %}

<!-- Showcase text for homepage -->
{% block page-title %}<h1>{{ game.game_title }}</h1>{% endblock %}
{% block page-subtitle %}{%endblock %}

{% block appcontent %}
<h4 class="info-head">Developer</h4>
<ul class="details">
    <li>{{ game.game_developer }}</li>
</ul>
<h4 class="info-head">Release Date</h4>
<ul class="details">
    <li>{{ game.game_release }}</li>
</ul>
<h4 class="info-head">Your Rating</h4>
<ul class="details">
     <li>{{ game.rating }}</li>
</ul>
<h4 class="info-head">Genre</h4>
<ul class="details">
     <li>{{ game.game_genre }}</li>
</ul>
<h4 class="info-head">Platform</h4>
<ul class="details">
     <li>{{ game.game_platform }}</li>
</ul>
{% endblock %}

{% block button1 %}<a href="{% url 'updateGame' game.id %}" class="contact-btn">Update</a>{% endblock %}
{% block button2 %}<a href="{% url 'deleteGame' game.id %}" onclick="return myFunction()" class="contact-btn">Delete</a>
{% endblock %}
{% block button3 %}<a href="{% url 'vgLibrary' %}" class="contact-btn">Library</a>{% endblock %}

{%  block javascript %}
    {{ block.super }}
    <script>
        function myFunction() {
            window.confirm("Do you really want to delete {{ game.game_title }} from your library?")
        }
    </script>
{% endblock %}

As you can see from the template I am just using a basic confirm function to give some sort of confirmation, but that doesn't even work as if I click cancel it still goes through. My guess is it has something to do with the delete view using a GET method instead of a Post method.

Upvotes: 0

Views: 410

Answers (1)

Ted Brownlow
Ted Brownlow

Reputation: 1117

window.confirm returns a Boolean indicating whether the user clicked confirm. This value is false if the user clicked cancel. You need to only open deleteGame if the user confirmed.

function myFunction() {
    if (window.confirm("Do you really want to delete {{ game.game_title }} from your library?")) {
        window.location.href="{% url 'deleteGame' game.id %}";
    }
}

Upvotes: 1

Related Questions