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.
0👍
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")
- [Answer]-Django cannot read session under subdomain but working under IP Address
- [Answer]-Django template: filter in an other
- [Answer]-Django admin fails using TabularInline
- [Answer]-Django – default value migration – will this touch database?
- [Answer]-Django template rendering extend tag incorrectly
0👍
I want to modify an answer from above which can be more easier…. i think 🙂 haha:
def register(request):
alert = {
"username": request.GET.get('username', ''),
}
if request.method == 'POST':
username = request.POST.get('username', '')
if User.objects.filter(username = request.POST['username']).exists():
alert['username'] = "Username already exists"
return render(request, 'interface/signup.html', alert)
and in your html: lets just say –>
<form method="POST"> {% csrf_token %}
<h3>Sign Up</h3>
<label class="label">Username:</label><input type="text" name="username" class="form-control" /><br>
{% if username %}
<div class="alert alert-danger alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
{{ username }}
</div>
<br>
{% endif %}
</form>
0👍
def register(request):
form = UserCreationForm(request.POST)
if form.is_valid():
else:
# Form is invalid, this includes the user already existing
I know it’s 2 years late but none of the answers had it and django has a built in way of solving it.
- [Answer]-How to make a record read-only in a Django form?
- [Answer]-Validate at least One check box is checked in django html template via Ajax
- [Answer]-Running django application on port 80 using nginx
- [Answer]-How to host django project in ubuntu using wsgi_mod
- [Answer]-Determining a Model Has Been Deleted
Source:stackexchange.com