About Django using Jquery asynchronous refresh

GET request

Jquery code (call view to send mailbox verification code)

 (document).ready(function() {
    // Get button to send verification code
    var btn =('#send_code');
    // Set button to disabled state
    btn.prop('disabled', true);

    // Monitor changes in the email input box
    ('#email').on('input', function() {
        // enable button
        btn.prop('disabled', false);
    });

    // Click the button to send verification code
    btn.click(function() {
        // Get the email entered by the user
        var email =('#email').val();

        // sendajaxask,Send verification code to email
        $.ajax({
            url: "/user/send_code/", // Change it to the backend interface address according to your actual situation.
            data: {'email': email},
            type: 'GET',
            dataType: 'json',
            success: function(data) {
                if (data.status === 'success') {
                    // Sent successfully,Show prompt information,Disable button,Countdown
                    btn.text('Sent successfully');
                    btn.prop('disabled', true);
                    var seconds = 60;
                    var timer = setInterval(function() {
                        seconds -= 1;
                        btn.text(seconds + 'Can be resent after seconds');
                        if (seconds === 0) {
                            // Countdown ends,enable button,reset text
                            btn.prop('disabled', false);
                            btn.text('Send the verification code');
                            clearInterval(timer);
                        }
                    }, 1000);
                } else {
                    // Failed to send,Show prompt information
                    btn.text('Failed to send,Please try again');
                }
            }
        });

        // Block button default behavior
        return false;
    });
});

The python code (view function, used to generate a random CAPTCHA)

def send_code(request):
    # Used to create verification code objects
    res = {'status': 'success', 'info': 'ok'}
    email = request.GET['email']
    code = ''
    for i in range(6):
        n = random.randint(0, 9)
        b = chr(random.randint(65, 90))
        s = chr(random.randint(97, 122))
        code += str(random.choice([n, b, s]))

    mail.send_mail("Verification code", code, sender, recipient_list=[email])
    checkcode.objects.create(email=email, code=code, create_time=time.time())
    return JosnResponse(res)

POST request

Jquery code (send data validation request and jump)

$('#submit').on('click', function() {
    const username = $('#username').val();
    const password = $('#password').val();
    const code = $('#code').val();
    const career = $('#careers').val();
    const email = $('#email').val();

    $.ajax({
        url: '/user/register/', // Change it to the backend interface address according to your actual situation.
        type: 'POST',
        data: JSON.stringify({ username, password, email, career, code }),
        contentType: 'application/json',
        success: function(data) {
            console.log(data);  // print out in consoledataContent
            if (data.status == 'error') {
                alert(data.message); // Display error message
            } else {
                alert('User registered successfully'); // Show success message
                window.location.href = '/index'; // Redirect to another page
            }
        },
        error: function(xhr, status, error) {
            console.error('Error during registration:', error);
        }
    });
    return false;
}); 

Python code (data validation, database storage)

def register(request):
    if request.method == 'GET':
        return render(request, 'login/register.html')
    elif request.method == 'POST':
        data = json.loads(request.body)
        email = data.get('email')
        username = data.get('username')
        code = data.get('code')
        password = data.get('password')
        career = data.get('career')

        res = {'status': 'error', 'message': ''}
        #  Verify that the user exists
        try:  # Exclude index duplication caused by concurrent writes,identicaluesrnameinsert
            old_users = User.objects.filter(email=email)
        except Exception as e:
            res['message'] = 'User already exists'
            return JsonResponse(res)

        if old_users:
            res['message'] = 'User already exists'
            return JsonResponse(res)

        #  Check whether the verification code has expired
        codes = checkcode.objects.filter(email=email, is_active=True)
        if not codes:
            res['message'] = 'Verification code not sent or invalid'
            return JsonResponse(res)

        sign = False
        for real in codes:
            real.is_active = False
            real.save()
            oldtime = float(real.create_time)
            if (time.time() - oldtime) <= 300 and code == real.code:
                sign = True

        if not sign:
            res['message'] = 'No valid verification code was obtained or the verification code was wrong.'
            return JsonResponse(res)

        l1 = len(username)
        if l1 > 10:
            res['message'] = 'Username length is illegal'
            return JsonResponse(res)

        # Hash passwords
        pwd = hashlib.md5()
        pwd.update(password.encode())
        pwd_new = pwd.hexdigest()

        User.objects.create(username=username, email=email, password=pwd_new, career=career)
        request.session['username'] = username
        request.session['email'] = email

        res['status'] = 'success'
        res['message'] = 'registration success'
        return JsonResponse(res)

Brief summary

For those who may need to stay on the original page and keep the original state, Jquery can save a lot of work on the front end.

Because regular view functions return either HttpResponse or HttpRedirectResponse

This kind of response will be rendered directly on the HTML page, which is not in line with our business logic.

Define a dictionary in the view function, and the dictionary type can be converted to Json Response without reporting an error

The response result in the front end must be JSON data (otherwise the call to the data attribute cannot be made).

In other words, the response body returned by the backend must be a Json Response. It is not enough to use only the JSON. Dumps (res), and the frontend still cannot adjust to the correct response result

For routing in Django

Personally, as long as it does not affect the situation, want to save a little trouble, for the route that can not be accessed (whether there is a slash at the end will lead to various errors), you can write the slash and no slash, that is the safest way to write, because there is no need for Django to help us complete the slash at the end (if it is Django to help us complete). Access is equivalent to redirection. If it is still a post request at this time, it will cause data loss.) Therefore, it is better to write both forms in the routing.