Session variable not being updated in django , only taking the first value

this view that sends a confirmation code to the email, each time it is executed it generates a new code-reset variable perfectly

def codeSender(request,user):


    code = random.randint(100000, 999999)

    request.session['reset_code'] = code
    request.session.save()
    print(request.session['reset_code']) 

    # will print a new code each time this view is being executed
    
    request.session['user'] = user.pk  

    subject = "Password reset"
    message = render_to_string('authentication/emailResetPassword.html', {'code': code})

    email = EmailMessage(
        subject,
        message,
        settings.EMAIL_HOST_USER,
        to=[user.email]
    )
    email.send()

this view is supposed to take the value of the username verify if it exists and then call the codeSender() view all along returning a json response indicating that the code confirmation form will be shown

def resetPassword(request):

    if request.method == 'POST':
        form_name = request.POST.get('form_name') 
        
        if form_name == "form1":
            username = request.POST["username"]

            userQuery = User.objects.filter(username=username)
            if not userQuery.exists():
                
                clear_messages(request) 
                
                messages.error(request, "You need to create an account, username doesn't exist!")

                serialized_messages = json.dumps([{
                'message': message.message,
                'message_tag': message.tags,
                } for message in messages.get_messages(request)])

                response_data = {
                    'show_form2': False,
                    'messages': serialized_messages}
                
            else:
                user = userQuery.first()
                
                codeSender(request,user)
            
                messages.success(request, "we've sent to your email a confirmation code please write it")
                
                serialized_messages = json.dumps([{
                'message': message.message,
                'message_tag': message.tags,
                } for message in messages.get_messages(request)])

                response_data = {
                    'show_form2': True,
                    'messages': serialized_messages}
                
            return JsonResponse(response_data)
    return render(request, "authentication/resetPassword.html")

the problem lays here , in this view im comparing the code entered by the user to see if it matches the reset_code ( the session variable ) , if it doesnt match i tried to simulate the form1 behavior so i can render again the code Confirmation form but the thing is , it always compares the entered code to the first code generated by codeSender in the session , it is not updating it unless I refresh the reset url again

def verify_code(request):   
     user_pk=request.session.get('user')
     user=User.objects.filter(pk=user_pk).first()
     if request.method == "POST" :
         codetrial = request.POST.get("code")
         if int(codetrial) == request.session.get('reset_code'):
             return redirect("resetConfirm")
         else:
             clear_messages(request)
             messages.error(request,'code doesnt match!, we sent you another code try again')


             data = {'username':user.username, 'form_name': "form1"}
             session = requests.Session()
             resp = session.get('http://127.0.0.1:8000/reset')
             csrf_token = resp.cookies['csrftoken']
             resp2 = session.post('http://127.0.0.1:8000/reset', data=data, headers={'X-CSRFToken': csrf_token})
             return render(request, 'authentication/resetPassword.html', {'json_data': resp2.text ,'identifier': 'view1'})
     else:
         return render(request,"authentication/resetPasswordConfirm.html",{"user":user.username})


here are the urls

    path('reset',views.resetPassword,name='reset'),
    path('verify',views.verify_code,name='verify'),

and here is the template, there are 2 forms form1 that takes the username input if it exists the resetCode view shows the form2 that ( the code confirmation form ) that is responsible for handling the code sent to the email

{% load static tailwind_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>reset password</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />

{% tailwind_css %}
</head>
<body>



<div class="flex flex-col mx-auto my-auto justify-center w-1/2 p-8  bg-gray-500 rounded-lg shadow ">

    <h3 class="font-bold text-white  text-5xl " >password reset</h3>
    
    <form action="{% url 'reset'  %}" name="form1" id="form1" method="POST">
        {% csrf_token %}
        <div class="py-1">
            <input class="focus:outline-none w-full p-1 border border-gray-300 rounded-md placeholder:font-light placeholder:text-gray-500 placeholder:text-sm pl-2"
            type="text" name="username" id="" placeholder="username" required>
        </div>
        <div class="flex justify-between w-full py-4">
            <div class="mr-24">
              <span class="text-md text-gray-400"> FORM1Dont'have an account? </span>
              <a class="font-bold text-black"><a href="/signup" class="font-bold">Sign up </a></span>
            </div>
            <span class="font-bold text-md"><a  href="{% url 'signin' %}"class="font-bold">sign in </a></span>
        </div>
        <button class="w-full bg-black text-white p-2 rounded-lg mb-6 hover:bg-blue-400 hover:text-white  "
        type="submit" >
           submit
        </button>

    </form> 

    <form action="{% url 'verify'  %}" name="form2" id="form2" class="hidden" method="POST">
        {% csrf_token %}
        <div class="py-1">
            <input class="focus:outline-none w-full p-1 border border-gray-300 rounded-md placeholder:font-light placeholder:text-gray-500 placeholder:text-sm pl-2"
            type="number" name="code" id="" placeholder="type the code !" required>
        </div>
        <div class="flex justify-between w-full py-4">
            <div class="mr-24">
              <span class="text-md text-gray-400"> Dont'have an account? </span>
              <a class="font-bold text-black"><a href="/signup" class="font-bold">Sign up </a></span>
            </div>
            <span class="font-bold text-md"><a  href="{% url 'signin' %}"class="font-bold">sign in</a></span>
        </div>
        <button class="w-full bg-black text-white p-2 rounded-lg mb-6 hover:bg-blue-400 hover:text-white  "
        type="submit" >
           submit
        </button>
    </form>



        
    <div id="outer-container" class="hidden flex flex-col space-y-4 relative rounded-lg bg-blue-400 overflow-hidden">
        <button type="button" class="absolute top-2 right-2 " onclick="this.parentElement.remove()">
                <i class="fa-solid fa-circle-xmark text-white "></i>
            </button>

            <div class="flex p-4 text-sm  text-white">
                <div class="flex-1">
                    <ul id="messages_list" class="mt-1 list-disc list-inside">
                        {% if show %}
                        {% if messages %}
                        {% for message in messages %}
                        <li>{{ message }}</li>
                        {% endfor %}
                        {% endif %}
                        {% endif %}


                    </ul>
                </div>
            </div>
        </div>
        

    

</div>
<script>
    function showForm2(response) {
         if (response.show_form2) {
             document.getElementById('form2').classList.remove('hidden');
             document.getElementById('form1').classList.add('hidden');

             const outerContainer = document.getElementById('outer-container');
             if (!outerContainer.classList.contains("hidden")) {
              outerContainer.classList.add("hidden");
              }
            //  in case the user types a wrong user name and then a  right one we need to remove the error messages on the page

         }
     }
     function showMessages(messages) {
    // Update the HTML of the error message container
    const outerContainer = document.getElementById('outer-container');
    outerContainer.classList.remove("hidden")

    const messagesContainer = document.getElementById('messages_list');
    console.log(messagesContainer)
    messagesContainer.innerHTML = "";

    messages.forEach(message => {
        console.log(message.message)
        const liItem= document.createElement('li');
        liItem.textContent = message.message;
        messagesContainer.append(liItem)
      
     })
}

const identifier = '{{ identifier|escapejs }}';
console.log( identifier)

// Handle the JSON data as in case of simulating the form1
if (identifier === 'view1'){
    const jsonData = JSON.parse('{{ json_data|escapejs }}');
if (jsonData.show_form2) {
    console.log("cccccccccccc")
    showForm2(jsonData);
}
if (jsonData.messages) {
    const messages = JSON.parse(jsonData.messages);
    showMessages(messages);
}
}
     // Submit form 1 
     document.getElementById('form1').addEventListener('submit', function(event) {
         event.preventDefault(); // Prevent default form submission
         var form = this;
         var formData = new FormData(form);
         formData.append('form_name', 'form1');
 
 
         fetch(form.action, {
             method: 'POST',
             body: formData,
             headers: {
                 'X-CSRFToken': '{{ csrf_token }}'
             }
         })
         .then(response => response.json())
         .then(data => {
    if (data.show_form2) {
        showForm2(data);
    }
    if (data.messages) {
        const messages = JSON.parse(data.messages);

        showMessages(messages);
    }
}).catch(error => console.error('Error:', error));
     });



 </script>
 
</body>

</html>


Back to Top