I have a regsitration form where a user chooses a plan. I am trying to check that if the field is empty a message should be displayed. The field name is plan. The code is below
if password1==password2:
if CustomUser.objects.filter(email=email).exists():
messages.info(request, 'User with same email already exists')
return redirect('register')
elif plan is None:
messages.info(request, 'Please select a plan')
return redirect('register')
else:
user=CustomUser.objects.create_user(full_name=full_name.upper(),age=age, phone_no=phone_no, address=address, plan=plan, email=email.lower(), password=password1)
user.is_active = False
user.save()
usr_otp = random.randint(100000, 999999)
UserOtp.objects.create(user = user, otp = usr_otp)
mess = f"Hello, {user.full_name},\n Please enter the otp to validate your email and activate your account. \nYour OTP is {usr_otp} .\n Thanks!"
return render(request, 'register.html', {'otp': True, 'user': user})
# return redirect('login')
I have tried multiple ways to check whether the plan field is empty or not such as
elif plan == ' '
elif not plan
elif plan is None
elif request.POST['plan'] == ' '
for all these I am getting only one error
MultiValueDictKeyError at /account/register
'plan'
Request Method: POST
Request URL: http://127.0.0.1:8000/account/register
Django Version: 3.2.8
Exception Type: MultiValueDictKeyError
Exception Value:
'plan'
Exception Location: C:\Users\rickb\Envs\virenv\lib\site-packages\django\utils\datastructures.py, line 78, in __getitem__
Python Executable: C:\Users\rickb\Envs\virenv\Scripts\python.exe
Python Version: 3.9.7
Python Path:
['C:\\Users\\rickb\\Envs\\virenv\\jgs',
'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\Users\\rickb\\Envs\\virenv',
'C:\\Users\\rickb\\Envs\\virenv\\lib\\site-packages']
Server time: Mon, 06 Dec 2021 23:30:33 0530
I don't understand why I am getting this, Please correct me what I am doing wrong and how to check that the plan field is empty.
The plan field in the html is a radio button that passes a value
CodePudding user response:
Try this instead:
elif request.POST.get('plan') == ' '
In python square brackets give error if there is no entry whereas get function returns None..
CodePudding user response:
If the plan field is empty, the key 'plan'
won't exist in request.POST
. So to verify if this field is empty you can do this
elif request.POST.get('plan') is None:
Since get
will return None
if the plan field is empty.