How can I Set Django Session Variable on one view and get it on another

Viewed 46

I am really confused on how to set and get Django Session variable. The most confusing part is that I want my application to set the PIN form field value as a session variable on my PIN activation view and get it on my guest registration view so I can save in model field. The reason is that I don't want the guest to repeat the PIN input on the registration page. Below are my views and how I am setting the session variable on my pin_activation view:

def pin_activation(request):

if request.method == "POST":
    
    #Create new form with name form
    form = PinActivationForm(request.POST)
    #Get User Pin Value from Form
    pin_value = form['pin'].value()
    #Check if the the form has valid data in it
    if form.is_valid():
        try:
            #Get user Pin with the one in the Database
            check_pin_status = Pin.objects.get(value=pin_value)
        except Pin.DoesNotExist:
            messages.error(request, f'{pin_value} Does Not Exist')
            return redirect('pin-activation')
        else:

            #Check PIN status
            if check_pin_status:
                #Get Event Ticket Date of the PIN
                event_date = check_pin_status.ticket.event.date
                #Get Current Date
                current_date = datetime.now().date()
                
                #Check if Event Date is Passed the Current Date
                if event_date < current_date:
                    messages.error(request, 'Event Has Passed')
                    return redirect('pin-activation')
                #Check if Event Ticket is Already Validated
                elif Pin.objects.filter(value=form['pin'].value(), status="Validated"):
                    messages.error(request, 'Pin Already Validated. Register for Seat')
                    return redirect('register-guest')
                #Check if PIN is ready Activated
                elif  Pin.objects.filter(value=form['pin'].value(), status="Activated"):
                    messages.error(request, "Pin Already Activated, Login.")
                    return redirect('user-login')  

                else:
                    #Update the User Pin with a new status of Activated
                    Pin.objects.filter(value=form['pin'].value()).update(status='Validated')
                    #Set PIN session
                    request.session['pin'] = form['pin'].value()
                    #Message the User
                    messages.success(request, 'Pin Validated Successfully')
                    #Redirect the user to register for seat
                    return redirect('register-guest')             
            #Check filter the DB where the PIN status is Validated
                           
    else:
        messages.error(request, 'Something Went Wrong. Try again')
else:
    form = PinActivationForm()
context = {
    'form':form,
}
return render(request, 'user/pin_activation.html', context)

And here is how I am getting the session variable on my registration view:

def register_guest(request):
pin = request.session.get('pin')
#Create variable and query all users
#user_pins = Pin.objects.all()
form = GuestUserForm() 
pin_form = PinActivationForm()
page_title = "Festival Registration"
if request.method == 'POST':
    form = GuestUserForm(request.POST) 
    pin_form = PinActivationForm(request.POST)
    if form.is_valid() and pin_form.is_valid():
        #Save the Guest User Form to get an instance of the user
        new_user = form.save()
        #Create A New Guest
        Guest.objects.create(guest_name=new_user, pin=pin) 
        #Filter and update PIN
        
        Pin.objects.filter(value=pin).update(status='Activated')
        messages.success(request, 'Registered Successfully. Login')
        return redirect('user-login')
else:
    form = GuestUserForm()
    
context = {
    'form':form,
    
    'page_title':page_title,
}
return render(request, 'user/register.html', context)

Please understand that my settings.py file has everything concerning sessions intact but the issue is only about getting the PIN Value saved in model through session. Thanks in anticipation for your answer.

2 Answers

Thanks to everyone that helped in sending his/her answer. Actually I was able to print out the value of the session on the proceeding view (as one of the answers suggested) and it outputted fine. And I went further to check my conditional statement in the request_guest view and I discovered that two forms were being checked in my conditional statement ( form.is_valid() and pin_form.is_valid(): ) whereas only one of them was in use ( form = GuestUserForm(request.POST) ) so I had to remove the form that was no longer in use and the everything worked well using session as shown below:

Pin Activation view:

def pin_activation(request):
        pin = request.session['pin']

Guest Registration view:

def register_guest(request):
    pin = request.session.get('pin')

Below is the new complete code for the register_guest view:

def register_guest(request):
    pin = request.session.get('pin')
    form = GuestUserForm() 
    if request.method == 'POST':
        form = GuestUserForm(request.POST)
        if form.is_valid():
    #Save the Guest User Form to get an instance of the user
        new_user = form.save()
        Guest.objects.create(guest_name=new_user, pin=pin) 
    Pin.objects.filter(value=pin).update(status='Activated')
    messages.success(request, 'Registered Successfully. Login')
    return redirect('user-login')
else:
    form = GuestUserForm()
context = {
    'form':form,
    
}

return render(request, 'user/register.html', context)

To set the session variable:

request.session['key'] = value

To retrieve the variable from the session:

request.session['key']

Related