[ In Django registration, if username already exists do something ]
this is a very basic and quick question in Django.
So in my views, where I am handling the registration, if a user tries to register with a username that already exists I want to just give a message, like a span next to the form, saying, "wrong username".
How do I print that message?
Thank you.
This is my part of code:
def register(request):
if request.method == 'POST':
if User.objects.filter(username = request.POST['username']).exists():
#I want to show next to the username textfield in registration form,
#a span for example that says "Wrong Username"
Answer 1
As suggested in a comment above, you should do it in form's clean method which would make things easier. But if you must do it in a view, here's an example:
if request.method == 'POST':
try:
user_exists = User.objects.get(username=request.POST['username'])
return HttpResponse("Username already taken")
except User.DoesNotExist:
# Username doesn't exist
# Do other validation ...
Then show the response in a span
using jQuery, or something else.
Answer 2
To get HTTPResponse message, you have to use ajax instead form submit.
Here i am assuming you are using following like html page code.
<input type="text" name="username" id="username"/> <p id="error"></p>
<input type="button" value="Register" id="register">
Now, You have to make an ajax call on button's click event like:
(i assume that you have knowledge of ajax call.)
$("#register").on('click', function(){
var username=$("#username").val();
$.ajax({
.
.
.
success: fuinction(data){
if(data=="error occured"){
$("error").append("wrong username");
}
}
})
});
and views.py code is like this:
def register(request):
if request.method == 'POST':
if User.objects.filter(username = request.POST['username']).exists():
return HTTPResponse("error occured")