Hello in my login site I have a form that sends a POST request on submit.
this is how I handle the forms POST request in my view
def SignUp(request):
if request.method == 'POST':
stuff goes here
else:
form = SignUpForm()
return render(request, "index.html", {"form": form})
now in my javascript i want to add another POST request that'll check if the current username within a certain is already taken. I made it and sent the POST to my current view where both this POST request will be handled along with the form POST request. what ends up happening is that SignUp() keeps handling both the POST requests. How do I handle two POST requests in one view? Is there a better way to do all of this? (i would preferably want to stay on this url)
tried to read about any way to differentiate between POST requests but found nothing. (i started learning django just a few days ago and im completely lost trying to make this work)
The most usual way would be to use different URL paths for each POST request. This means having one URL for the sign-up form submission and another URL for the username availability check. (I recommend to inspect similar web application behaviors by using Developer tools -> Network tab, while they are doing similar thing)
Best practice and recommended way: Using different URL for username_check
:
In urls.py
from django.urls import path
from .views import SignUp, check_username
urlpatterns = [
path('signup/', SignUp, name='signup'),
path('check_username/', check_username, name='check_username'),
]
In views.py
def check_username(request):
if request.method == 'POST':
# Handle the username check
...
If you still want to do it in the same URL, not best practice but it is possible by checking the request.POST content. For example, if the username check only sends the username, while the sign-up sends other fields like email and password, you could do:
def SignUp(request):
if request.method == 'POST':
if 'username' in request.POST and 'email' not in request.POST:
# This must be the username check
...
else:
# This must be the sign-up form
...
else:
form = SignUpForm()
return render(request, "index.html", {"form": form})
Lastly, I recommend to research about implenting API views, REST structure and Django Rest Framework as a learning path for this type of "background" features.