Javascript can't post data to database

from django.contrib import messages
from django.contrib.auth import get_user_model, login, logout
from django.contrib.auth.views import LoginView
from django.shortcuts import HttpResponseRedirect
from django.urls import reverse_lazy
from django.views.generic import TemplateView, RedirectView
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .forms import UserRegistrationForm, UserAddressForm
from .models import KeystrokeData

User = get_user_model()


@csrf_exempt
def save_keystroke_data(request):
    if request.method == 'POST':
        # Extract data from the POST request
        keystrokes_data = request.POST.get('inputPhrase', '')  # Match the field name in the HTML form
        
        # Save the keystroke data to the database
        KeystrokeData.objects.create(data=keystrokes_data)
        
        # Return a JSON response indicating success
        return JsonResponse({'status': 'success'})
    else:
        # Return a JSON response indicating failure (only accept POST requests)
        return JsonResponse({'status': 'error', 'message': 'Method not allowed'}, status=405)



class UserRegistrationView(TemplateView):
    model = User
    form_class = UserRegistrationForm
    template_name = 'accounts/user_registration.html'

    def dispatch(self, request, *args, **kwargs):
        if self.request.user.is_authenticated:
            return HttpResponseRedirect(reverse_lazy('transactions:transaction_report'))
        return super().dispatch(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        registration_form = UserRegistrationForm(self.request.POST)
        address_form = UserAddressForm(self.request.POST)

        if registration_form.is_valid() and address_form.is_valid():
            user = registration_form.save()
            address = address_form.save(commit=False)
            address.user = user
            address.save()

            login(self.request, user)
            messages.success(
                self.request,
                (
                    f'Thank You For Creating A Bank Account. '
                    f'Your Account Number is {user.account.account_no}. '
                )
            )
            return HttpResponseRedirect(reverse_lazy('transactions:deposit_money'))

        return self.render_to_response(
            self.get_context_data(
                registration_form=registration_form,
                address_form=address_form
            )
        )

    def get_context_data(self, **kwargs):
        if 'registration_form' not in kwargs:
            kwargs['registration_form'] = UserRegistrationForm()
        if 'address_form' not in kwargs:
            kwargs['address_form'] = UserAddressForm()

        return super().get_context_data(**kwargs)


class UserLoginView(LoginView):
    template_name = 'accounts/user_login.html'
    redirect_authenticated_user = True


class LogoutView(RedirectView):
    pattern_name = 'home'

    def get_redirect_url(self, *args, **kwargs):
        if self.request.user.is_authenticated:
            logout(self.request)
        return super().get_redirect_url(*args, **kwargs)


from django.urls import path

from .views import UserRegistrationView, LogoutView, UserLoginView
from . import views

app_name = 'accounts'

urlpatterns = [
    path(
        "login/", UserLoginView.as_view(),
        name="user_login"
    ),
    path(
        "logout/", LogoutView.as_view(),
        name="user_logout"
    ),
    path(
        "register/", UserRegistrationView.as_view(),
        name="user_registration"
    ),
    path('save-keystroke-data/', views.save_keystroke_data, name='save_keystroke_data'),
]

{% extends 'core/base.html' %}

{% block head_title %}Banking System{% endblock %}

{% block content %}
{% if registration_form.non_field_errors %}
    {% for error in registration_form.non_field_errors %}
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mt-2" role="alert">
        <p class="font-bold">Error!</p>
        <p class="block sm:inline">{{ error }}</p>
    </div>
    {% endfor %}
{% endif %}
{% if address_form.non_field_errors %}
    {% for error in address_form.non_field_errors %}
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mt-2" role="alert">
        <p class="font-bold">Error!</p>
        <p class="block sm:inline">{{ error }}</p>
    </div>
    {% endfor %}
{% endif %}

<h1 class="font-mono font-bold text-3xl text-center pb-5 pt-10">Register</h1>
<hr />
<div class="w-full mt-10">
    <form method="post" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" id="registrationForm">
       

        {% csrf_token %}
        {% for hidden_field in registration_form.hidden_fields %}
            {{ hidden_field.errors }}
            {{ hidden_field }}
        {% endfor %}
        <div class="flex flex-wrap -mx-3 mb-6">
            <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
                <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{ registration_form.first_name.id_for_label }}">
                    {{ registration_form.first_name.label }}
                </label>
                {{ registration_form.first_name }}
                {% if registration_form.first_name.errors %}
                    {% for error in registration_form.first_name.errors %}
                        <p class="text-red-600 text-sm italic pb-2">{{ error }}</p>
                    {% endfor %}
                {% endif %}
            </div>
            <div class="w-full md:w-1/2 px-3">
                <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{ registration_form.last_name.id_for_label }}">
                    {{ registration_form.last_name.label }}
                </label>
                {{ registration_form.last_name }}
                {% if registration_form.last_name.errors %}
                    {% for error in registration_form.last_name.errors %}
                        <p class="text-red-600 text-sm italic pb-2">{{ error }}</p>
                    {% endfor %}
                {% endif %}
            </div>
        </div>
        <div class="flex flex-wrap -mx-3 mb-6">
            <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
                <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{ registration_form.email.id_for_label }}">
                    {{ registration_form.email.label }}
                </label>
                {{ registration_form.email }}
                {% if registration_form.email.errors %}
                    {% for error in registration_form.email.errors %}
                        <p class="text-red-600 text-sm italic pb-2">{{ error }}</p>
                    {% endfor %}
                {% endif %}
            </div>
            <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
                <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{ registration_form.account_type.id_for_label }}">
                    {{ registration_form.account_type.label }}
                </label>
                {{ registration_form.account_type }}
                {% if registration_form.account_type.errors %}
                    {% for error in registration_form.account_type.errors %}
                    <p class="text-red-600 text-sm italic pb-2">{{ error }}</p>
                    {% endfor %}
                {% endif %}
            </div>
        </div>
        <div class="flex flex-wrap -mx-3 mb-6">
            <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
                <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{ registration_form.gender.id_for_label }}">
                    {{ registration_form.gender.label }}
                </label>
                {{ registration_form.gender }}
                {% if registration_form.gender.errors %}
                    {% for error in registration_form.gender.errors %}
                        <p class="text-red-600 text-sm italic pb-2">{{ error }}</p>
                    {% endfor %}
                {% endif %}
            </div>
            <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
                <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{ registration_form.birth_date.id_for_label }}">
                    {{ registration_form.birth_date.label }}
                </label>
                {{ registration_form.birth_date }}
                {% if registration_form.birth_date.errors %}
                    {% for error in registration_form.birth_date.errors %}
                    <p class="text-red-600 text-sm italic pb-2">{{ error }}</p>
                    {% endfor %}
                {% endif %}
            </div>
        </div>
        <div class="flex flex-wrap -mx-3 mb-6">
            <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
                <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{ registration_form.password1.id_for_label }}">
                    {{ registration_form.password1.label }}
                </label>
                {{ registration_form.password1 }}
                {% if registration_form.password1.errors %}
                    {% for error in registration_form.password1.errors %}
                        <p class="text-red-600 text-sm italic pb-2">{{ error }}</p>
                    {% endfor %}
                {% endif %}
            </div>
            <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
                <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{ registration_form.password2.id_for_label }}">
                    {{ registration_form.password2.label }}
                </label>
                {{ registration_form.password2 }}
                    {% if registration_form.password2.errors %}
                    {% for error in registration_form.password2.errors %}
                        <p class="text-red-600 text-sm italic pb-2">{{ error }}</p>
                    {% endfor %}
                {% endif %}
            </div>
        </div>

        {% for hidden_field in address_form.hidden_fields %} {{ hidden_field.errors }} {{ hidden_field }} {% endfor %}
        <div class="flex flex-wrap -mx-3 mb-6">
            <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
                <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{ address_form.street_address.id_for_label }}">
                    {{ address_form.street_address.label }}
                </label>
                {{ address_form.street_address }}
                {% if address_form.street_address.errors %}
                    {% for error in address_form.street_address.errors %}
                        <p class="text-red-600 text-sm italic pb-2">{{ error }}</p>
                    {% endfor %}
                {% endif %}
            </div>
            <div class="w-full md:w-1/2 px-3">
                <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{ address_form.city.id_for_label }}">
                    {{ address_form.city.label }}
                </label>
                {{ address_form.city }}
                {% if address_form.city.errors %}
                    {% for error in address_form.city.errors %}
                        <p class="text-red-600 text-sm italic pb-2">{{ error }}</p>
                    {% endfor %}
                {% endif %}
            </div>
        </div>
        <div class="flex flex-wrap -mx-3 mb-6">
            <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
                <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{ address_form.postal_code.id_for_label }}">
                    {{ address_form.postal_code.label }}
                </label>
                {{ address_form.postal_code }}
                {% if address_form.postal_code.errors %}
                    {% for error in address_form.postal_code.errors %}
                        <p class="text-red-600 text-sm italic pb-2">{{ error }}</p>
                    {% endfor %}
                {% endif %}
            </div>
            <div class="w-full md:w-1/2 px-3">
                <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{ address_form.country.id_for_label }}">
                    {{ address_form.country.label }}
                </label>
                {{ address_form.country }}
                {% if address_form.country.errors %}
                    {% for error in address_form.country.errors %}
                        <p class="text-red-600 text-sm italic pb-2">{{ error }}</p>
                    {% endfor %}
                {% endif %}
            </div>

            <div class="w-full md:w-1/2 px-3">
                <label class="block lowercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="inputPhrase">
                    Please type "cyber resilience 2024" 20 times:
                </label>
                <textarea id="inputPhrase" name="inputPhrase" rows="10" cols="50" class="border rounded-md px-3 py-2" onkeyup="sendDataToServer(this.value.slice(-1), new Date().toISOString())"></textarea>
                <div id="phraseError" class="hidden text-red-600 text-sm italic pb-2">Please type "cyber resilience 2024" 20 times.</div>

            </div>
            

        </div>
        <div>
            <input type="hidden" id="keystrokesData" name="keystrokesData">
        </div>
        


        <div class="flex items-center justify-between">
            <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="submit">
                Register
            </button>
        </div>
    </form>
</div>
<script>
document.getElementById('registrationForm').addEventListener('submit', function(event) {
    var inputPhrase = document.getElementById('inputPhrase').value;
    var phraseCount = (inputPhrase.match(/cyber resilience 2024/g) || []).length;

    // Prevent form submission if phrase count is insufficient
    if (phraseCount < 20 || isPasted) {
        event.preventDefault();
        document.getElementById('phraseError').classList.remove('hidden');
    }
});

// Add event listener for paste event
document.getElementById('inputPhrase').addEventListener('paste', function(event) {
    var pastedText = (event.clipboardData || window.clipboardData).getData('text');
    if (pastedText.includes('cyber resilience 2024')) {
        event.preventDefault();
        alert("Pasting is not allowed! Please type");
    }
});
</script>
<script>
    // Initialize an empty array to store keystrokes
    var keystrokes = [];
    
    function sendDataToServer() {
        // Check if the typed phrase matches the desired phrase
        var typedPhrase = keystrokes.join('');
        if (typedPhrase === 'cyber resilience 2024') {
            // Create FormData object
            var data = new FormData();
            // Append keystrokes array as a single key
            data.append('keystrokes', typedPhrase);
            // Get the current timestamp
            var timestamp = new Date().toISOString();
            // Append timestamp
            data.append('timestamp', timestamp);
    
            // Create XMLHttpRequest object
            var xhr = new XMLHttpRequest();
            // Open POST request to save-keystroke-data endpoint
            xhr.open('POST', '/save-keystroke-data/', true);
            // Define onload function
            xhr.onload = function() {
                if (xhr.status === 200) {
                    console.log('Keystroke data sent successfully.');
                } else {
                    console.error('Failed to send keystroke data. Status: ' + xhr.status);
                }
            };
            // Send data
            xhr.send(data);
            // Reset keystrokes array for the next batch
            keystrokes = [];
        }
    }
    
    // Add event listener for keyup event
    document.getElementById('inputPhrase').addEventListener('keyup', function(event) {
        // Append the typed character to the keystrokes array
        keystrokes.push(event.key);
        // Send data to server
        sendDataToServer();
    });
    </script>
    


{% endblock %}

could you review my views.py, urls.py and the registration form?