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)
3
Answers
You need to use another route. URI’s are used to create hierarchical addresses for endpoints where functionality is handled. Since you want to use another POST, you need to have another route for it to go to. Here is an example of a routing structure (restful) for a web API for data and users.
Handle data actions
Handle user actions
Notice there are different HTTP Verbs (GET,PUT,POST, DELETE) handled at each endoint, but never twice at an endpoint.
I think Flask is a better place to start off with some of these concepts. Here is a blog article about Flask and routing.
https://auth0.com/blog/developing-restful-apis-with-python-and-flask/
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
In views.py
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:
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.
If you need to know a username is already taken or not you can simply do it with overriding clean method of your form:
check this > https://docs.djangoproject.com/en/4.2/ref/forms/validation/
btw the best way to keep your field unique is to put
unique=True
in your model field. I hope it helped.