Reputation: 105
There is a URL with an endpoint named as 'otp/'
, I don't want the user to access this endpoint directly, I want to have them as directed by my code (whenever needed)
How can I do it?
here is my code
class OTPView(View):
def get(self, request, *args, **kwargs):
otp_form = OTP_Form()
return render(request, 'otp.html', {'otp_form': otp_form})
def post(self, request, *args, **kwargs):
try:
otp = request.session.get('otp')
first_name = request.session.get('first_name')
last_name = request.session.get('last_name')
password = request.session.get('password')
phone = request.session.get('phone')
otp_form = OTP_Form(request.POST)
if otp_form.is_valid():
get_otp = otp_form.cleaned_data['otp']
if get_otp == otp:
user = MyUser.objects.create_user(
phone=phone, password=password, first_name=first_name, last_name=last_name)
user.save()
otp_entry = OTP.objects.create(user_id=user, otp=otp)
otp_entry.save()
delete_session(request)
messages.success(
request, 'Your account has been created')
return redirect('login')
else:
messages.error(request, 'Incorrect OTP')
return redirect('otp')
else:
messages.error(request, 'Please enter the OTP again')
return redirect('otp')
except:
messages.error(request, 'Please try signing up again')
return redirect('signup')
urls.py
path('otp/', OTPView.as_view(), name='otp'),
I want this endpoint to be accessed by the user right after the user signup
Please suggest me something
Upvotes: 0
Views: 611
Reputation: 1412
There is easy way to do it just in get method check referrer:
def get(self, request, *args, **kwargs):
if request.META['HTTP_REFERER'] != '/mylogin/':
return HttpResponseForbidden()
otp_form = OTP_Form()
return render(request, 'otp.html', {'otp_form': otp_form})
You need to check if reffering url is your signup url
Upvotes: 1
Reputation: 1045
if you do not want it to be an API and want to handle it only inside the code, then there is no need of registering this function to any route path. Just use it as a signal after the user signup.
Django Signals: https://docs.djangoproject.com/en/4.0/topics/signals/
post_save
signal can be helpful for your case.
Upvotes: 1
Reputation: 143
The idea itself sounds weird, that isn't how HTTP should work. You can restrict views based on permissions but not on the state. Consider putting such logic in the function instead of view or do some condition check inside view based on some info (you can store data in session or cookie for example, and check it in view).
Upvotes: 1