Как я могу установить переменную сессии Django в одном представлении и получить ее в другом

Я действительно запутался в том, как установить и получить переменную сессии Django. Наиболее запутанной частью является то, что я хочу, чтобы мое приложение установило значение поля формы PIN как переменную сессии на моем представлении активации PIN и получило его на моем представлении регистрации гостя, чтобы я мог сохранить в поле модели. Причина в том, что я не хочу, чтобы гость повторял ввод PIN-кода на странице регистрации. Ниже приведены мои представления и то, как я устанавливаю переменную сессии в представлении pin_activation:

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', pin=pin_value)             
            #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)

А вот как я получаю переменную сессии в моем представлении регистрации:

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)

Пожалуйста, поймите, что в моем файле settings.py есть все, что касается сессий, но вопрос только в том, чтобы получить значение PIN, сохраненное в модели через сессию. Спасибо в ожидании вашего ответа.

Для установки переменной сессии вы можете использовать request.session['pin'] = form['pin'].value(), как объясняется в документации Django здесь https://docs.djangoproject.com/en/4.1/topics/http/sessions/#examples

Чтобы установить переменную сеанса:

request.session['key'] = value

Чтобы получить переменную из сессии:

request.sessiom['key']

Спасибо всем, кто помог, прислав свой ответ. На самом деле я смог вывести значение сессии в представлении proceeding (как было предложено в одном из ответов), и оно было выведено нормально. И я пошел дальше, чтобы проверить мой условный оператор в представлении request_guest и обнаружил, что две формы проверялись в моем условном операторе ( form.is_valid() and pin_form.is_valid(): ), в то время как только одна из них использовалась ( form = GuestUserForm(request.POST) ), поэтому мне пришлось удалить форму, которая больше не использовалась, и все работало хорошо, используя сессию, как показано ниже:

Вид активации штифта:

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

Просмотр регистрации гостя:

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

Ниже приведен новый полный код для представления register_guest:

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)
Вернуться на верх