article

Saturday, November 14, 2020

Live Username Available using Python Flask MongoDB and Jquery Ajax


Live Username Available using Python Flask MongoDB and Jquery Ajax

if you start registration it will ask your username if no record found in the database Username not available if username available the message display Username Available and the registration button is disable 
app.py
#app.py
from flask import Flask, render_template, flash, redirect, url_for, request, json
from flask_mongoengine import MongoEngine #ModuleNotFoundError: No module named 'flask_mongoengine' = (venv) C:\flaskmyproject>pip install flask-mongoengine  
 
app = Flask(__name__)

app.config['MONGODB_SETTINGS'] = {
    'db': 'dbmongocrud',
    'host': 'localhost',
    'port': 27017
}
db = MongoEngine()
db.init_app(app)	
  
class User(db.Document):
    user_name = db.StringField()
    email = db.StringField()
    password = db.StringField()
	
@app.route('/',methods=['POST','GET'])
def index():
    message = ''
    if request.method == 'POST':
        # Get Form Fields
        _username = request.form['username']
        txtemail = request.form['txtemail']
        txtpass = request.form['txtpass']
        usersave = User(user_name=_username, email=txtemail, password=txtpass)
        usersave.save()
        message = 'Succefully Register'
    return render_template('checkusername.html', message=message)
 
@app.route('/check_username', methods=['POST'])
def check_username():
    if request.method == 'POST':
        username = request.form['username']
        total = User.objects(user_name=username).count()
        print(username)
        if total > 0:
            msg =  '{ "html":"Ok"}'
            msghtml = json.loads(msg)
            return msghtml["html"] 
        else:	
            msg =  '{ "html":"No found"}'
            msghtml = json.loads(msg)
            return msghtml["html"] 
	
if __name__ == '__main__':
    app.run(debug=True)
templates/checkusername.html
//templates/checkusername.html
<html>  
 <head>  
  <title>Live Username Available using Python Flask MongoDB and Jquery Ajax</title>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
  <style>  
  body  
  {  
   margin:0;  
   padding:0;  
   background-color:#f1f1f1;  
  }  
  .box  
  {  
   width:800px;  
   border:1px solid #ccc;  
   background-color:#fff;  
   border-radius:5px;
   margin-top:36px;  
  }  
  </style>  
 <script>  
$(function() {
    $('#username').blur(function(){
		var username = $(this).val();
        $.ajax({
            url: '/check_username',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response) {
                if(response == 'Ok'){
					$('#availability').html('<span class="text-success">Username Available</span>');
					$('#register').attr("disabled", true);
                }else{
					$('#availability').html('<span class="text-danger">Username not available</span>');
					$('#register').attr("disabled", false);
				}
            },
            error: function(error) {
                console.log(error);
            }
        });
    });
}); 
</script> 
 </head>  
 <body>  
  <div class="container box">  
   <div class="form-group">  
    <h3 align="center">Live Username Available using Python Flask MongoDB and Jquery Ajax</h3><br />  
	{% if message %}
          <div class="alert alert-success">{{message}}</div>
    {% endif %}
    <form class="form-signin" action="/" method="post">
	<label>Enter Username</label>  
    <input type="text" name="username" id="username" class="form-control" />
    <span id="availability"></span>
    <br />
	<label>Enter Email</label>  
    <input type="text" name="txtemail" id="txtemail" class="form-control" />
	<label>Enter Password</label>  
    <input type="text" name="txtpass" id="txtpass" class="form-control" />
	<br />
    <button type="submit" name="register" class="btn btn-info" id="register" disabled>Register</button>
	</form>
    <br />
   </div>  
   <br />  
   <br />  
  </div>  
 </body>  
</html>  

Related Post