for the second reason, i can assure you that the session variable was set, because if not, then the user would not even see the registration view. Here's the complete code.
# ---------- REGISTER A BUILDER ------------
# enter the phone no to verify to continue with registration
def mobileDetail_builder(request):
context = {}
logout(request)
if request.POST:
# setting this to 0 ensures that upon entering the phone number, user must verify the otp
# to set it to 1.
request.session['verified'] = 0
mobile_form = mobileForm(request.POST)
if mobile_form.is_valid():
phone = mobile_form.cleaned_data.get('phone')
Status, id = send_otp(phone)
if Status == 'Success':
request.session['id']=id
request.session['phone']=phone
return redirect('otp_builder')
else:
messages.error(request,'OTP NOT SENT, PLEASE TRY AGAIN WITH VALID PHONE NUMBER')
return redirect('mobile_verify_builder')
else:
context['mobile_form'] = mobile_form
else:
mobile_form = mobileForm()
context['mobile_form'] = mobile_form
return render(request,'accounts/mobile.html',context)
# verify otp
def otp_verify_builder(request):
context = {}
id = request.session['id']
print(id)
if request.POST:
otp_form = otp_verification_form(request.POST)
if otp_form.is_valid():
otp = otp_form.cleaned_data.get('otp')
status = check_otp(otp,id)
if status == 'Success':
# this is to ensure that if user goes directly to the url of registration after
# entering the phone no, he/she cant register without the otp verification
request.session['verified'] = 1
return redirect('register_builder')
else:
raise ValueError('ENTER CORRECT OTP')
else:
context['otp_form'] = otp_form
else:
otp_form = otp_verification_form()
context['otp_form'] = otp_form
return render(request,'accounts/otp_builder.html',context)
def register_builder(request):
verified_phone = request.session['phone']
context = {'phone': request.session['phone']}
if request.POST:
form = BuilderRegistrationForm(request.POST)
# this is to confirm that the user does not change the value of the phone number and
# only uses the verified one
phone1 = form['phone'].value()
if form.is_valid() and request.session['verified']==1 and verified_phone==phone1:
user=form.save()
user.is_builder = True
user.save()
phone = form.cleaned_data.get('phone')
raw_password = form.cleaned_data.get('password1')
account = authenticate(phone=phone, password=raw_password, is_builder=True)
login(request, account)
return redirect('builder_index')
else:
context['registration_form']=form
else:
form = BuilderRegistrationForm()
form['phone'].initial=request.session['phone']
context['registration_form'] = form
return render(request, 'accounts/register_builder.html',context)