data not saving to the database in the frontend

Blockquote

{% extends "base.html" %}
{% load static %}

{% block title %}Create Account{% endblock %}

{% block content %}
<div class="create-account-container">
    <h2>Create Account</h2>
    <form action="{% url 'create_account' %}" method="POST" id="account_form">
        {% csrf_token %}
        <div class="create-account-form-group">
            <label>User Role:</label>
            <label for="admin">Admin</label>
            <input type="radio" id="admin" name="role" value="admin" required>
            <label for="staff">Staff</label>
            <input type="radio" id="staff" name="role" value="staff" required>
        </div>

        <div id="create-admin-account-form" class="create-account-form-group" style="display: none;">
            <!-- Admin Account Creation Form -->
            <label for="admin_username">Username:</label>
            <input type="text" id="admin_username" name="username" autocomplete="username" placeholder="Enter your username" required>
            <label for="admin_country">Country:</label>
            <select id="admin_country" name="country" required>
                <option value="" disabled selected>Select your country</option>
                <!-- Country options will be dynamically added here -->
            </select>
            <label for="admin_mobile_number">Mobile Number:</label>
            <div class="create_account_mobile_group">
                <input type="text" id="admin_country_code" name="admin_country_code" autocomplete="tel-country-code" placeholder="Country code" required style="width: 30%;">
                <input type="text" id="admin_mobile_number" name="mobile_number" autocomplete="tel-national" placeholder="Enter your mobile number" required style="width: 70%;">
            </div>
            <label for="admin_email">Email:</label>
            <input type="email" id="admin_email" name="email" autocomplete="email" placeholder="Enter your email" required>
            <label for="admin_password">Password:</label>
            <input type="password" id="admin_password" name="password" autocomplete="new-password" placeholder="Enter your password" required>
            <label for="admin_confirm_password">Confirm Password:</label>
            <input type="password" id="admin_confirm_password" name="password_confirmation" autocomplete="new-password" placeholder="Confirm your password" required>
            <button type="submit" id="create_admin_account_btn" class="create-account-btn">Create account</button>
        </div>

        <div id="staff-auth-form" class="create-account-form-group" style="display: none;">
            <!-- Staff Authentication Form -->
            <label for="school_code">School Code:</label>
            <input type="text" id="school_code" name="school_code" placeholder="Enter school code" required>
            <button type="button" id="check_code_btn">Check Code</button>
        </div>

        <div id="create-staff-account-form" class="create-account-form-group" style="display: none;">
            <!-- Staff Account Creation Form -->
            <label for="staff_username">Username:</label>
            <input type="text" id="staff_username" name="username" autocomplete="username" placeholder="Enter your username" required>
            <label for="country">Country:</label>
            <select id="country" name="country" required>
                <option value="" disabled selected>Select your country</option>
                <!-- Country options will be dynamically added here -->
            </select>
            <label for="staff_mobile_number">Mobile Number:</label>
            <div class="create_account_mobile_group">
                <input type="text" id="staff_country_code" name="staff_country_code" autocomplete="tel-country-code" placeholder="Country code" required style="width: 30%;">
                <input type="text" id="staff_mobile_number" name="mobile_number" autocomplete="tel-national" placeholder="Enter your mobile number" required style="width: 70%;">
            </div>
            <label for="staff_email">Email:</label>
            <input type="email" id="staff_email" name="email" autocomplete="email" placeholder="Enter your email" required>
            <label for="staff_password">Password:</label>
            <input type="password" id="staff_password" name="password" autocomplete="new-password" placeholder="Enter your password" required>
            <label for="staff_confirm_password">Confirm Password:</label>
            <input type="password" id="staff_confirm_password" name="password_confirmation" autocomplete="new-password" placeholder="Confirm your password" required>
            <button type="submit" id="create_staff_account_btn" class="create-account-btn">Create account</button>
        </div>
    </form>
</div>
{% endblock %}

{% block script %}   
<script src="{% static "SCRIPTS/create_account.js" %}"></script>
{% endblock %}

Blockquote

from django.db import models
from schools_app.models import School

class Country(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class CountryCode(models.Model):
    country = models.OneToOneField(Country, on_delete=models.CASCADE)
    code = models.CharField(max_length=10)

    def __str__(self):
        return f"{self.country.name} - {self.code}"

class User(models.Model):
    ROLE_CHOICES = [
        ('admin', 'Admin'),
        ('staff', 'Staff'),
    ]

    username = models.CharField(max_length=150, unique=True)
    role = models.CharField(max_length=5, choices=ROLE_CHOICES)
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    mobile_number = models.CharField(max_length=15)
    email = models.EmailField(unique=True)
    password = models.CharField(max_length=128)
    school = models.ForeignKey(School, on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return self.username

Blockquote

import json  # Import the json module
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from .models import User, Country, CountryCode
from schools_app.models import School  # Import the School model
from .forms import UserAdminForm
from django.views.decorators.csrf import csrf_exempt  # Import csrf_exempt decorator
from django.contrib.auth.hashers import make_password  # Import make_password

@csrf_exempt  # Add this decorator to exempt CSRF token requirement for this view
def create_account(request):
    if request.method == 'POST':
        form = UserAdminForm(request.POST)
        if form.is_valid():
            role = form.cleaned_data['role']
            username = form.cleaned_data['username']
            country_id = form.cleaned_data['country'].id
            country = Country.objects.get(pk=country_id)
            country_code_obj = CountryCode.objects.get(country=country)
            country_code = country_code_obj.code
            mobile_number = form.cleaned_data['mobile_number']
            email = form.cleaned_data['email']
            password = make_password(form.cleaned_data['password'])
            confirm_password = form.cleaned_data['password_confirmation']

            if form.cleaned_data['password'] != confirm_password:
                return JsonResponse({'success': False, 'error': 'Passwords do not match'})

            if role == 'admin':
                User.objects.create(
                    username=username,
                    role='admin',
                    country=country,
                    mobile_number=mobile_number,
                    email=email,
                    password=password,
                    school=None
                )
            elif role == 'staff':
                school_code = form.cleaned_data['school_code']
                try:
                    school = School.objects.get(code=school_code)
                    User.objects.create(
                        username=username,
                        role='staff',
                        country=country,
                        mobile_number=mobile_number,
                        email=email,
                        password=password,
                        school=school
                    )
                except School.DoesNotExist:
                    return JsonResponse({'success': False, 'error': 'Invalid school code'})
            return JsonResponse({'success': True, 'redirect_url': '/success_page/'})
        else:
            return JsonResponse({'success': False, 'error': 'Invalid form data'})
    else:
        form = UserAdminForm()

    return render(request, 'account/create_account.html', {'form': form})

@csrf_exempt
def validate_school_code(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        school_code = data.get('school_code')
        try:
            School.objects.get(code=school_code)
            return JsonResponse({'valid': True})
        except School.DoesNotExist:
            return JsonResponse({'valid': False})
    return JsonResponse({'valid': False})

Blockquote

// START OF CREATE ACCOUNT AUTHENTICATION

document.addEventListener('DOMContentLoaded', function() {
// COUNTRY CODE SETTING

// Define the list of countries and their corresponding dialing codes
const countries = [
    {"name": "Afghanistan", "code": "+93"},
    {"name": "Albania", "code": "+355"},
    {"name": "Zimbabwe", "code": "+263"}
    // Add more countries as needed
  ];
 

  function getCountryCode(countryName) {
    const country = countries.find(c => c.name === countryName);
    return country ? country.code : '';
}

function updateCountryCode(selectElement, inputElement) {
    selectElement.addEventListener('change', function() {
        const selectedOption = selectElement.options[selectElement.selectedIndex];
        const countryCode = getCountryCode(selectedOption.text);
        inputElement.value = countryCode;
    });
}

const adminCountrySelect = document.getElementById('admin_country');
const adminCountryCodeInput = document.getElementById('admin_country_code');
const staffCountrySelect = document.getElementById('country');
const staffCountryCodeInput = document.getElementById('staff_country_code');

if (adminCountrySelect && adminCountryCodeInput) {
    updateCountryCode(adminCountrySelect, adminCountryCodeInput);
}

if (staffCountrySelect && staffCountryCodeInput) {
    updateCountryCode(staffCountrySelect, staffCountryCodeInput);
}

const roleInputs = document.querySelectorAll('input[name="role"]');
roleInputs.forEach(input => {
    input.addEventListener('change', function() {
        const adminForm = document.getElementById('create-admin-account-form');
        const staffAuthForm = document.getElementById('staff-auth-form');
        const staffForm = document.getElementById('create-staff-account-form');

        if (this.value === 'admin') {
            adminForm.style.display = 'block';
            staffAuthForm.style.display = 'none';
            staffForm.style.display = 'none';

            setRequiredAttributes(adminForm, true);
            setRequiredAttributes(staffAuthForm, false);
            setRequiredAttributes(staffForm, false);
        } else if (this.value === 'staff') {
            adminForm.style.display = 'none';
            staffAuthForm.style.display = 'block';
            staffForm.style.display = 'none';

            setRequiredAttributes(adminForm, false);
            setRequiredAttributes(staffAuthForm, true);
            setRequiredAttributes(staffForm, false);
        }
    });
});

function setRequiredAttributes(form, isRequired) {
    const inputs = form.querySelectorAll('input, select');
    inputs.forEach(input => {
        if (isRequired) {
            input.setAttribute('required', 'required');
        } else {
            input.removeAttribute('required');
        }
    });
}

function populateCountryDropdown(countrySelectId, countryCodeFieldId, selectedCountry = "") {
    const countrySelect = document.getElementById(countrySelectId);
    const countryCodeField = document.getElementById(countryCodeFieldId);

    countrySelect.innerHTML = "";

    const defaultOption = document.createElement("option");
    defaultOption.value = "";
    defaultOption.disabled = true;
    defaultOption.selected = true;
    defaultOption.textContent = "Select your country";
    countrySelect.appendChild(defaultOption);

    countries.forEach(country => {
        const option = document.createElement("option");
        option.value = country.code;
        option.textContent = country.name;
        if (selectedCountry === country.code) {
            option.selected = true;
            countryCodeField.value = country.code;
        }
        countrySelect.appendChild(option);
    });

    countrySelect.addEventListener("change", () => {
        const selectedOption = countrySelect.options[countrySelect.selectedIndex];
        countryCodeField.value = selectedOption.value;
    });
}

function showAdditionalFields() {
    const adminRadio = document.getElementById("admin");
    const staffRadio = document.getElementById("staff");
    const createAdminForm = document.getElementById("create-admin-account-form");
    const staffAuthForm = document.getElementById("staff-auth-form");
    const createStaffForm = document.getElementById("create-staff-account-form");

    if (adminRadio.checked) {
        createAdminForm.style.display = "block";
        staffAuthForm.style.display = "none";
        createStaffForm.style.display = "none";

        populateCountryDropdown("admin_country", "admin_country_code");
        setRequiredAttributes(createAdminForm, true);
        setRequiredAttributes(staffAuthForm, false);
        setRequiredAttributes(createStaffForm, false);
    } else if (staffRadio.checked) {
        createAdminForm.style.display = "none";
        staffAuthForm.style.display = "block";
        createStaffForm.style.display = "none";

        populateCountryDropdown("country", "staff_country_code");
        setRequiredAttributes(createAdminForm, false);
        setRequiredAttributes(staffAuthForm, true);
        setRequiredAttributes(createStaffForm, false);
    } else {
        createAdminForm.style.display = "none";
        staffAuthForm.style.display = "none";
        createStaffForm.style.display = "none";
        setRequiredAttributes(createAdminForm, false);
        setRequiredAttributes(staffAuthForm, false);
        setRequiredAttributes(createStaffForm, false);
    }

    document.querySelectorAll('.create-account-form-group input').forEach(input => {
        input.setCustomValidity('');
    });
}

const adminRadio = document.getElementById("admin");
const staffRadio = document.getElementById("staff");
adminRadio.addEventListener("change", showAdditionalFields);
staffRadio.addEventListener("change", showAdditionalFields);

populateCountryDropdown("admin_country", "admin_country_code");
populateCountryDropdown("country", "staff_country_code");

const checkCodeButton = document.getElementById("check_code_btn");
if (checkCodeButton) {
    checkCodeButton.addEventListener("click", validateSchoolCode);
}

document.getElementById('account_form').addEventListener('submit', function(event) {
    event.preventDefault(); 

    const role = document.querySelector('input[name="role"]:checked');
    if (!role) {
        alert("Please select a role.");
        return;
    }

    if (role.value === 'admin') {
        handleAdminAccountCreation();
    } else if (role.value === 'staff') {
        if (document.getElementById('staff-auth-form').style.display === 'block') {
            alert("Please validate the school code first.");
        } else {
            handleStaffAccountCreation();
        }
    }
});

function validateSchoolCode() {
    const schoolCodeInput = document.getElementById("school_code");
    const schoolCode = schoolCodeInput.value.trim();

    fetch("/validate_school_code/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": getCookie("csrftoken")
        },
        body: JSON.stringify({ school_code: schoolCode })
    })
    .then(response => response.json())
    .then(data => {
        if (data.valid) {
            document.getElementById("staff-auth-form").style.display = "none";
            document.getElementById("create-staff-account-form").style.display = "block";

            populateCountryDropdown("country", "staff_country_code");
            setRequiredAttributes(document.getElementById('create-staff-account-form'), true);
        } else {
            alert("Invalid school code");
        }
    })
    .catch(error => {
        console.error("Error validating school code:", error);
        alert("An error occurred while validating the school code. Please try again later.");
    });
}

function handleAdminAccountCreation() {
    // Gather the admin form data
    const adminForm = document.getElementById('create-admin-account-form');
    const formData = new FormData(adminForm);

    fetch('/create_account/', {
        method: 'POST',
        body: formData,
        headers: {
            "X-CSRFToken": getCookie("csrftoken")
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.location.href = data.redirect_url;
        } else {
            alert(data.error);
        }
    })
    .catch(error => {
        console.error('Error creating admin account:', error);
        alert('An error occurred while creating the admin account. Please try again later.');
    });
}

function handleStaffAccountCreation() {
    // Gather the staff form data
    const staffForm = document.getElementById('create-staff-account-form');
    const formData = new FormData(staffForm);

    fetch('/create_account/', {
        method: 'POST',
        body: formData,
        headers: {
            "X-CSRFToken": getCookie("csrftoken")
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.location.href = data.redirect_url;
        } else {
            alert(data.error);
        }
    })
    .catch(error => {
        console.error('Error creating staff account:', error);
        alert('An error occurred while creating the staff account. Please try again later.');
    });
}

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
});

Blockquote

In the admin panel, I am able to save the data into the database but in the frontend, my code is not able to save the data into the database.

Side note: When posting code here, enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted. Make sure the lines of ``` are lines by themselves - not part of any other line. Also ensure you use the backtick - ` and not the apostrophe - ' or quote - " characters.
(I’ve taken the liberty of fixing your original post for you.)

noted, thank you. Do I have to repost?

No, unless I made a mistake in adding the backticks. (And if I did, I think you would still be able to edit the post.)