article

Friday, April 10, 2020

Python Django Forms and Validation


Python Django Forms and Validation

Django Form Validation - Django provides built-in methods to validate form data automatically. Django forms submit only if it contains CSRF tokens. It uses uses a clean and easy approach to validate data.

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

Sql table
CREATE TABLE employee (
id INTEGER PRIMARY KEY,
name STRING (100),
contact STRING (100)
);
#models.py
from django.db import models

# Create your models here.
class Employee(models.Model):  
    name = models.CharField(max_length=100)  
    contact = models.CharField(max_length=100)  
    class Meta:  
        db_table = "employee"  
#forms.py
from django import forms  
from myapp.models import Employee  
  
class EmployeeForm(forms.ModelForm):  
    class Meta:  
        model = Employee  
        fields = "__all__"  
#view.py
from django.shortcuts import render, redirect

# Create your views here.
from myapp.forms import EmployeeForm  

def index(request): 
    if request.method == "POST":
        form = EmployeeForm(request.POST)
        if form.is_valid():
            model_instance = form.save(commit=False)
            model_instance.save()
            return redirect('/')
    else:
        form = EmployeeForm()
        return render(request, "index.html", {'form': form})
//templates/index.html
<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Index</title>  
</head>  
<body>  
<form method="POST" class="post-form" enctype="multipart/form-data">  
        {% csrf_token %}  
        {{ form.as_p }}  
        <button type="submit" class="save btn btn-default">Save</button>  
</form>  
</body>  
</html> 

urls.py
from myapp import views 

urlpatterns = [
    path('admin/', admin.site.urls),   
    path('', views.index),   
]

Thursday, April 9, 2020

Python Django Forms


Python Django Forms - Django provides a Form class which is used to create HTML forms. It describes a form and how it works and appears.

Forms.py
 
from django import forms
 
COUNTRY_CHOICES =( 
    ("1", "Philippines"), 
    ("2", "Japan"), 
    ("3", "Korea"), 
    ("4", "Singapore"), 
    ("5", "USA"), 
)
CHOICES=[('male','Male'),
         ('female','Female')]

class StudentForm(forms.Form):  
    firstname = forms.CharField(label="Enter first name",max_length=50)  
    lastname  = forms.CharField(label="Enter last name", max_length = 100)  
    country  = forms.ChoiceField(choices = COUNTRY_CHOICES)
    date  = forms.DateField()
    age = forms.DecimalField()
    email = forms.EmailField()
    photo = forms.FileField()
    gender = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) 
    accept  = forms.BooleanField(label="Accept privacy and terms")
 
    def __str__(self):
        return self.firstname
Views.py
 
from django.shortcuts import render, redirect

# Create your views here.
from django import forms
from myapp.forms import StudentForm  
  
def index(request):  
    student = StudentForm()  
    return render(request,"form.html",{'form':student})   
Forms.html
<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Django Forms</title>  
</head>  
<body>  
<p><h2>Django Forms</h2></p>
<form method="POST" class="post-form">  
        {% csrf_token %}  
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Save</button>  
</form> 
</body>  
</html>

urls.py

from django.contrib import admin
from django.urls import path
from myapp import views 

urlpatterns = [
    path('admin/', admin.site.urls),   
    path('index', views.index),   
    #path('', views.index),   
]

Wednesday, April 8, 2020

Django Model Forms - How to use bootstrap in django forms


Django Model Forms - How to use bootstrap in django forms

Django Model Form - It is a class which is used to create an HTML form by using the Model


Database Table

CREATE TABLE myapp_contact (
id INTEGER NOT NULL
PRIMARY KEY AUTOINCREMENT,
name VARCHAR (255),
email VARCHAR (254) NOT NULL,
subject VARCHAR (255),
message TEXT,
createdAt DATETIME NOT NULL

);

Models.py
 
from django.db import models

# Create your models here.
class Contact(models.Model):
    name = models.CharField("First name", max_length=255, blank = True, null = True)
    email = models.EmailField()
    subject = models.CharField("Subject", max_length=255, blank = True, null = True)
    message = models.TextField(blank=True, null=True)
    createdAt = models.DateTimeField("Created At", auto_now_add=True)

    def __str__(self):
        return self.name
Views.py
 
from django.shortcuts import render, redirect

# Create your views here.
from django import forms
from django.utils import timezone
from myapp.forms import MyCommentForm
def index(request):
 
    if request.method == "POST":
        form = MyCommentForm(request.POST)
        if form.is_valid():
            model_instance = form.save(commit=False)
            model_instance.timestamp = timezone.now()
            model_instance.save()
            return redirect('/index')
    else:
        form = MyCommentForm()
        return render(request, "my_template.html", {'form': form})
Forms.py
 
from django.forms import ModelForm
from myapp.models import Contact
from django import forms
  
class MyCommentForm(forms.ModelForm):
    class Meta(object):
        model = Contact
        fields = ['name', 'email', 'subject', 'message']
        widgets = {
            'name': forms.TextInput(
    attrs={
     'class': 'form-control'
     }
    ),
   'email': forms.TextInput(
    attrs={
     'class': 'form-control'
     }
    ),
   'subject': forms.TextInput(
    attrs={
     'class': 'form-control'
     }
    ),
            'message': forms.Textarea(
    attrs={
     'class': 'form-control'
     }
    ),
   }
my_template.html
<DOCTYPE html>
<html>
<head>
<title>Django Forms</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="jumbotron jumbotron-sm">
    <div class="container">
        <div class="row">
            <div class="col-sm-12 col-lg-12">
                <h1 class="h1">Contact us <small>Feel free to contact us</small></h1>
    <p style="font-weight:bold;color:red;">Django Model Forms - How to use bootstrap in django forms</p>
            </div>
        </div>
    </div>
</div>
<div class="container">
    <div class="row">
        <div class="col-md-8">
            <div class="well well-sm">
                <form action="" method="POST" role="form">
                {% csrf_token %}
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="name">
                                Name</label>
                            {{ form.name }}
                        </div>
                        <div class="form-group">
                            <label for="email">
                                Email Address</label>
                            <div class="input-group">
                                <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span>
                                </span>
                                {{ form.email }}</div>
                        </div>
                        <div class="form-group">
                            <label for="subject">
                                Subject</label>
                            <select id="subject" name="subject" class="form-control" required="required">
                                <option value="na" selected="">Choose One:</option>
                                <option value="service">General Customer Service</option>
                                <option value="suggestions">Suggestions</option>
                                <option value="product">Product Support</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="name">
                                Message</label>
                            {{ form.message }}
                        </div>
                    </div>
                    <div class="col-md-12">
                        <button type="submit" class="btn btn-primary pull-right" id="btnContactUs">
                            Send Message</button>
                    </div>
                </div>
                </form>
            </div>
        </div>
        <div class="col-md-4">
            <legend><span class="glyphicon glyphicon-globe"></span> Our office</legend>
            <address>
                <strong>Cairocoders, Inc.</strong><br>
                158 Folsom Ave, Suite 600<br>
                Olongapo City, CA 94107<br>
                <abbr title="Phone">
                    P:</abbr>
                (123) 456-7890
            </address>
            <address>
                <strong>Cairocoders</strong><br>
                <a href="mailto:#">cairocoders@example.com</a>
            </address>
        </div>
    </div>
</div>
</body>
</html>

Monday, April 6, 2020

Django basic Model View Template and static files handling


Django basic Model View Template and static files handling

Install Django Version 3.0.2 on windows 10 | Create Project and Setting Admin


Models.py


from django.db import models
from django.utils import timezone
from django.conf import settings

# Create your models here.

class Contact(models.Model):
    firstName = models.CharField("First name", max_length=255, blank = True, null = True)
    lastName = models.CharField("Last name", max_length=255, blank = True, null = True)
    email = models.EmailField()
    phone = models.CharField(max_length=20, blank = True, null = True)
    address = models.TextField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    createdAt = models.DateTimeField("Created At", auto_now_add=True)

    def __str__(self):
        return self.firstName
  
class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #models.ForeignKey – this is a link to another model.
    title = models.CharField(max_length=200)
    text = models.TextField() #models.TextField – this is for long text without a limit. Sounds ideal for blog post content, right?
    created_date = models.DateTimeField(default=timezone.now) #models.DateTimeField – this is a date and time.
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title
Settings.py
 
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

C:\my_project_django\devproject>python manage.py makemigrations myapp
C:\my_project_django\devproject>python manage.py migrate


Views.py
 
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse  
import datetime 
from django.template import loader 

def index(request):  
   template = loader.get_template('index.html') # getting our template  
   name = {  #Variable Example
       'student':'Cairocoders Ednalan'  
   } 
   return HttpResponse(template.render(name))       # rendering the template in HttpResponse  
   
#def index(request):  
#    now = datetime.datetime.now()   
#    html = "<html><body><h3>Now time is %s.</h3></body></html>" % now  
#    return HttpResponse(html)    # rendering the template in HttpResponse   

C:\my_project_django\devproject>python manage.py runserver

urls.py
from django.contrib import admin
from django.urls import path
from myapp import views  

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),    
]
templates/index.html
//index.html
<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Index</title>  
 {% load static %} 
 <script src="{% static '/js/script.js' %}" type="text/javascript"></script> 
    <link href="{% static 'css/style.css' %}" rel="stylesheet">  
</head>  
<body>  
<h1>Welcome to Django!!!</h1>  
<h3>My Name is: {{ student }}</h3>  
<img src="{% static '/test.jpg' %}"/>  
</body>  
</html>

static/js/script.js
alert('test javascript');

static/css/style.css
h1{ color:red;font-size:35px; }

Saturday, April 4, 2020

Python Flask Dynamic Select Box using Flask-WTF, javascript and SQLAlchemy


Python Flask Dynamic Select Box using Flask-WTF, javascript and SQLAlchemy

Database Table

CREATE TABLE countries (
id INTEGER PRIMARY KEY,
name STRING (60)

);

INSERT INTO countries (id, name) VALUES (171, 'Philippines');
INSERT INTO countries (id, name) VALUES (227, 'United States of America');

CREATE TABLE state (
id INTEGER PRIMARY KEY,
name STRING (60),
country_id INTEGER

);

INSERT INTO state (id, name, country_id) VALUES (1, 'ARMM', 171);
INSERT INTO state (id, name, country_id) VALUES (2, 'Bicol', 171);
INSERT INTO state (id, name, country_id) VALUES (3, 'Central Luzon', 171);
INSERT INTO state (id, name, country_id) VALUES (4, 'Central Mindanao', 171);
INSERT INTO state (id, name, country_id) VALUES (5, 'Alabama', 227);
INSERT INTO state (id, name, country_id) VALUES (6, 'Alaska', 227);
INSERT INTO state (id, name, country_id) VALUES (7, 'Arizona', 227);
INSERT INTO state (id, name, country_id) VALUES (8, 'California', 227);
INSERT INTO state (id, name, country_id) VALUES (9, 'Florida', 227);

CREATE TABLE city (
id INTEGER PRIMARY KEY,
state STRING (60),
name STRING (60),
stateid INTEGER

);

INSERT INTO city (id, state, name, stateid) VALUES (1, 'CA', 'Anaheim', 8);
INSERT INTO city (id, state, name, stateid) VALUES (2, 'NV', 'Arden-Arcade', 8);
INSERT INTO city (id, state, name, stateid) VALUES (3, 'CA', 'Bakersfield', 8);
INSERT INTO city (id, state, name, stateid) VALUES (4, 'CA', 'Carson', 8);
INSERT INTO city (id, state, name, stateid) VALUES (5, 'NV', 'Daly City', 8);
INSERT INTO city (id, state, name, stateid) VALUES (6, NULL, 'Angeles City', 3);
INSERT INTO city (id, state, name, stateid) VALUES (7, NULL, 'Olongapo', 3);
INSERT INTO city (id, state, name, stateid) VALUES (8, NULL, 'San Fernando', 3);
INSERT INTO city (id, state, name, stateid) VALUES (9, NULL, 'Tarlac', 3);
#app.py
from flask import Flask, render_template, request, jsonify, json
from flask_sqlalchemy import SQLAlchemy  
from wtforms import SelectField
from flask_wtf import FlaskForm

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db' 
app.config['SECRET_KEY'] = 'cairocoders-ednalan'

db = SQLAlchemy(app) 

class Country(db.Model):
    __tablename__ = 'countries'
 
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60))
 
class State(db.Model):
    __tablename__ = 'state'
 
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60))
    country_id = db.Column(db.Integer)
 
class City(db.Model):
 __tablename__ = 'city'

 id = db.Column(db.Integer, primary_key=True)
 name = db.Column(db.String(60))
 stateid = db.Column(db.Integer) 

class Form(FlaskForm):
    country = SelectField('country', choices=[])
    state = SelectField('state', choices=[])
    city = SelectField('city', choices=[])
        
@app.route('/', methods=['GET', 'POST'])
def index():
    form = Form()
    form.country.choices = [(country.id, country.name) for country in Country.query.all()]
 
    if request.method == 'POST':
       city = City.query.filter_by(id=form.city.data).first()
       country = Country.query.filter_by(id=form.country.data).first()
       state = State.query.filter_by(id=form.state.data).first()
       return '

Country : {}, State: {}, City: {}

'.format(country.name, state.name, city.name) return render_template('index.html', form=form) @app.route('/state/') def statebycountry(get_state): state = State.query.filter_by(country_id=get_state).all() stateArray = [] for city in state: stateObj = {} stateObj['id'] = city.id stateObj['name'] = city.name stateArray.append(stateObj) return jsonify({'statecountry' : stateArray}) @app.route('/city/') def city(get_city): state_data = City.query.filter_by(stateid=get_city).all() cityArray = [] for city in state_data: cityObj = {} cityObj['id'] = city.id cityObj['name'] = city.name cityArray.append(cityObj) return jsonify({'citylist' : cityArray}) if __name__ == '__main__': app.run(debug=True)
//templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Python Flask Dynamic Select Box using Flask-WTF, javascript and SQLAlchemy</title>
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="container">
 <div class="row">
        <div class="col-md-12">
        <p><h2>Python Flask Dynamic Select Box using Flask-WTF, javascript and SQLAlchemy</h2></p>
        <form method="POST">
          {{ form.csrf_token}}  
      <div class="form-group">
    <label for="email">Country:</label>
    {{ form.country(class="form-control") }}
   </div>
   <div class="form-group">
    <label for="email">State:</label>
    {{ form.state(class="form-control")}}
   </div>
   <div class="form-group">
    <label for="email">City:</label>
    {{ form.city(class="form-control")}} 
   </div>
    <input type="submit" class="btn btn-success" btn-lg>
  </form> 
        </div>
 </div>
</div> 
<script>
country_select = document.getElementById('country');
state_select = document.getElementById('state');
city_select = document.getElementById('city');

country_select.onchange = function(){
 country = country_select.value;
 <!-- alert(country); --> 
 fetch('state/' + country).then(function(response){
  response.json().then(function(data) {
   optionHTML = '';
   for (state of data.statecountry) {
    optionHTML += '<option value="' + state.id +'">' + state.name + '</option>'
   }
   state_select.innerHTML = optionHTML;
  });
 });
}
state_select.onchange = function(){
 city = state_select.value; 
 fetch('city/' + city).then(function(response){
  response.json().then(function(data) {
   optionHTML = '';
   for (city_rs of data.citylist) {
    optionHTML += '<option value="' + city_rs.id +'">' + city_rs.name + '</option>'
   }
   city_select.innerHTML = optionHTML;
  });
 });
}
</script>
</body>
</html>

Thursday, April 2, 2020

Python Flask Jquery Ajax Autocomplete using SQLAlchemy database


Python Flask Jquery Ajax Autocomplete using SQLAlchemy database

CREATE TABLE countries (
id INTEGER PRIMARY KEY,
name STRING (60)

);


 
#app.py
from flask import Flask, render_template, request, jsonify, json
from wtforms import StringField, TextField, Form
from wtforms.validators import DataRequired, Length
from flask_sqlalchemy import SQLAlchemy  

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db' 
app.config['SECRET_KEY'] = 'cairocoders-ednalan'

db = SQLAlchemy(app) 
 
class SearchForm(Form): #create form
 country = StringField('Country', validators=[DataRequired(),Length(max=40)],render_kw={"placeholder": "country"})

class Country(db.Model):
 __tablename__ = 'countries'

 id = db.Column(db.Integer, primary_key=True)
 name = db.Column(db.String(60), unique=True, nullable = False)

 def as_dict(self):
  return {'name': self.name}
  
@app.route('/')
def index():
 form = SearchForm(request.form)
 return render_template('search.html', form=form)

@app.route('/countries')
def countrydic():
 res = Country.query.all()
 list_countries = [r.as_dict() for r in res]
 return jsonify(list_countries)
 
@app.route('/process', methods=['POST'])
def process():
 country = request.form['country']
 if country:
  return jsonify({'country':country})
 return jsonify({'error': 'missing data..'})

if __name__ == '__main__':
    app.run(debug=True)
//search.html
<html>
<head>
    <meta charset="utf-8">
 <title>Python Flask Jquery Ajax Autocomplete</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  </head>
<body>
<h1>Python Flask Jquery Ajax Autocomplete using SQLAlchemy database</h1>
<form class="form-inline">
 <div class="form-group">
     {{form.country(class="form-control")}}
   </div>
   <button type="submit" class="btn btn-info">Submit</button>
</form>
<div id="result"></div>
<script>
$(document).ready(function(){
 var countries=[];
 function loadCountries(){
  $.getJSON('/countries', function(data, status, xhr){
   for (var i = 0; i < data.length; i++ ) {
    countries.push(data[i].name);
   }
 });
 };
 loadCountries();

 $('#country').autocomplete({
  source: countries, 
 }); 

 $('form').on('submit', function(e){
  $.ajax({
   data: {
    country:$('#country').val()
   },
   type: 'POST',
   url : '/process'
  })
  .done(function(data){ 
   if (data.error){
    $('#result').text(data.error).show();
   }
   else {
    $('#result').html(data.country).show()
   }
  })
  e.preventDefault();
 });
}); 
</script>
<style>
.form-control {
    display: block;
    width:300px;
    padding: .375rem .75rem;
    font-size: 1rem;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
.btn {padding: .375rem .75rem; margin-top:10px;}
</style>
  </body>
</html>

Python Flask Jquery Ajax Autocomplete


Python Flask Jquery Ajax Autocomplete

 
#app.py
from flask import Flask, Response, render_template, request
import json
from wtforms import TextField, Form

app = Flask(__name__)

class SearchForm(Form):
    autocomp = TextField('Insert City', id='city_autocomplete')


@app.route('/_autocomplete', methods=['GET'])
def autocomplete():
    cities = ["Olongapo City",
          "Angeles City",
          "Manila",
          "Makati",
          "Pasig",
          "Davao",
          "Cebu",
          "Quezon City",
          "Taguig"]
    print(cities)    
    return Response(json.dumps(cities), mimetype='application/json')


@app.route('/', methods=['GET', 'POST'])
def index():
    form = SearchForm(request.form)
    return render_template("search.html", form=form)

if __name__ == '__main__':
    app.run(debug=True)
//search.html
<head>
    <meta charset="utf-8">
 <title>Python Flask Jquery Ajax Autocomplete</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  </head>
<body>
{{ form.autocomp.label }}: {{ form.autocomp }}
<script>
    $(function() {
        $.ajax({
            url: '{{ url_for("autocomplete") }}'
            }).done(function (data){
                $('#city_autocomplete').autocomplete({
                    source: data,
                    minLength: 2
                });
            });
        });
</script>
  </body>
</html>

Sunday, March 29, 2020

Python Flask How to Delete Multiple records using checkbox with getlist and pymysql


Python Flask How to Delete Multiple records using checkbox with getlist and pymysql


#app.py
from flask import Flask, render_template, request
from flaskext.mysql import MySQL
import pymysql

app = Flask(__name__)
app.secret_key = "Cairocoders-Ednalan"
 
mysql = MySQL()
  
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'testingdb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

@app.route('/', methods=['GET', 'POST'])
def index():
    conn = mysql.connect()
    cur = conn.cursor(pymysql.cursors.DictCursor)
    msg = '' 
    if request.method == 'POST': 
        #test = request.form.getlist('mycheckbox')
        for getid in request.form.getlist('mycheckbox'):
            print(getid)
            cur.execute('DELETE FROM employee WHERE id = {0}'.format(getid))
            conn.commit()
            msg = 'Successfully Deleted'
        return render_template('index.html', msg=msg)
    return render_template('index.html')
 
//templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Python Flask How to Delete Multiple records using checkbox with getlist and pymysql</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="container">
 <div class="row">
        <div class="col-md-12">
        <p><h2>Python Flask How to Delete Multiple records using checkbox with getlist and pymysql</h2></p>
        <div class="table-responsive">
        <form method="POST" action="/">        
        <table id="mytable" class="table table-bordred table-striped">
            <thead>
                <th><input type="checkbox" id="checkall" /></th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Address</th>
                <th>Email</th>
                <th>Contact</th>
                <th>Edit</th>
    <th>Delete</th>
            </thead>
   <tbody>
   <tr>
    <td><input type="checkbox" value="21" name="mycheckbox" class="checkthis" /></td>
    <td>Airi</td>
    <td>Satou</td>
    <td>New Cabalan Olongapo City, Philippines</td>
    <td>cairocoders@gmail.com</td>
    <td>+923335586757</td>
    <td><p data-placement="top" data-toggle="tooltip" title="Edit"><button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit" ><span class="glyphicon glyphicon-pencil"></span></button></p></td>
    <td><p data-placement="top" data-toggle="tooltip" title="Delete"><button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete" ><span class="glyphicon glyphicon-trash"></span></button></p></td>
   </tr>
   <tr>
    <td><input type="checkbox" value="22" name="mycheckbox" class="checkthis" /></td>
    <td>Angelica</td>
    <td>Ramos</td>
    <td>New Cabalan Olongapo City, Philippines</td>
    <td>cairocoders0711@gmail.com</td>
    <td>+923335586757</td>
    <td><p data-placement="top" data-toggle="tooltip" title="Edit"><button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit" ><span class="glyphicon glyphicon-pencil"></span></button></p></td>
    <td><p data-placement="top" data-toggle="tooltip" title="Delete"><button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete" ><span class="glyphicon glyphicon-trash"></span></button></p></td>
   </tr>
   <tr>
    <td><input type="checkbox" value="23" name="mycheckbox" class="checkthis" /></td>
    <td>Ashton</td>
    <td>Cox</td>
    <td>New Cabalan Olongapo City, Philippines</td>
    <td>cairocoders0711@gmail.com</td>
    <td>+923335586757</td>
    <td><p data-placement="top" data-toggle="tooltip" title="Edit"><button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit" ><span class="glyphicon glyphicon-pencil"></span></button></p></td>
    <td><p data-placement="top" data-toggle="tooltip" title="Delete"><button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete" ><span class="glyphicon glyphicon-trash"></span></button></p></td>
   </tr>
   </tbody>
        
  </table><input type="submit" value="Delete All Selected" class="btn btn-primary">  
  <br/>
  {% if msg %}
  <div class="alert alert-danger" role="alert">{{ msg }}</div>
  {% endif %}
        </form>        
            </div>
            
        </div>
 </div>
</div>
<script>
$(document).ready(function(){
$("#mytable #checkall").click(function () {
        if ($("#mytable #checkall").is(':checked')) {
            $("#mytable input[type=checkbox]").each(function () {
                $(this).prop("checked", true);
            });

        } else {
            $("#mytable input[type=checkbox]").each(function () {
                $(this).prop("checked", false);
            });
        }
    });
    
    $("[data-toggle=tooltip]").tooltip();
});

</script>  
</body>
</html>

Thursday, March 26, 2020

Python Flask Upload File and validate before save to Database using SQLAlchemy


Python Flask Upload File and validate before save to Database using SQLAlchemy

Validate extension file before save to database
 
#app.py
from flask import Flask, render_template, flash, redirect, url_for, request
from flask_sqlalchemy import SQLAlchemy  
from werkzeug.utils import secure_filename
import os
#import magic
import urllib.request

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db' 
app.config['SECRET_KEY'] = 'cairocoders-ednalan'

UPLOAD_FOLDER = 'C:/flaskmyproject/demoapp/static'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
 
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
 
def allowed_file(filename):
 return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
 
db = SQLAlchemy(app) 

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(120), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True) 
    profile_pic = db.Column(db.String(150))
 

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['inputFile']
    rs_username = request.form['txtusername']
    filename = secure_filename(file.filename)
 
    if file and allowed_file(file.filename):
       file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
 
       newFile = User(profile_pic=file.filename, username=rs_username, email='Ednalan@gmail.com')
       db.session.add(newFile)
       db.session.commit()
       flash('File successfully uploaded ' + file.filename + ' to the database!')
       return redirect('/')
    else:
       flash('Invalid Uplaod only txt, pdf, png, jpg, jpeg, gif') 
    return redirect('/')    
 
if __name__ == '__main__':
    app.run(debug=True)
//templates/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Python Flask Upload File and validate before save to Database using SQLAlchemy </title>
  </head>
  <body>
  <h2>Python Flask Upload File and validate before save to Database using SQLAlchemy </h2>
  <h3>Select a file to upload</h3>
        <p>
         {% with messages = get_flashed_messages() %}
           {% if messages %}
          {% for message in messages %}
            <div class="alert alert-primary">
             <strong>{{ message }}</strong>
           </div>
          {% endfor %}
           {% endif %}
         {% endwith %}
        </p>
  <form method="post" action="/upload" enctype="multipart/form-data">
 <input type="text" name="txtusername" value="" placeholder="User Name" required>
    <dl>
  <p>
   <input type="file" name="inputFile" autocomplete="off" required>
  </p>
    </dl>
    <p>
  <input type="submit" value="Submit">
 </p>
</form>
<style>
.alert-primary {
    color: #004085;
    background-color: #cce5ff;
    border-color: #b8daff;
}
.alert {
    position: relative;
    padding: .75rem 1.25rem;
    margin-bottom: 1rem;
    border: 1px solid transparent;
    border-radius: .25rem;
}
</style>
    </body>
</html>

Registration Form With sqlite3 database using tkinter python



Registration Form With sqlite3 database using tkinter python

 
from tkinter import *
import sqlite3

root = Tk()
root.geometry('600x500')
root.title("Registration Form")


Fullname=StringVar()
Email=StringVar()
var = IntVar()
c=StringVar()
var1= IntVar()



def database():
   name1=Fullname.get()
   email=Email.get()
   gender=var.get()
   country=c.get()
   prog=var1.get()
   conn = sqlite3.connect('Form.db')
   with conn:
      cursor=conn.cursor()
   cursor.execute('CREATE TABLE IF NOT EXISTS Student (Fullname TEXT,Email TEXT,Gender TEXT,country TEXT,Programming TEXT)')
   cursor.execute('INSERT INTO Student (FullName,Email,Gender,country,Programming) VALUES(?,?,?,?,?)',(name1,email,gender,country,prog,))
   conn.commit()
   
   
             
label_0 = Label(root, text="Registration form",width=20,font=("bold", 20))
label_0.place(x=90,y=53)


label_1 = Label(root, text="FullName",width=20,font=("bold", 10))
label_1.place(x=80,y=130)

entry_1 = Entry(root,textvar=Fullname)
entry_1.place(x=240,y=130)

label_2 = Label(root, text="Email",width=20,font=("bold", 10))
label_2.place(x=68,y=180)

entry_2 = Entry(root,textvar=Email)
entry_2.place(x=240,y=180)

label_3 = Label(root, text="Gender",width=20,font=("bold", 10))
label_3.place(x=70,y=230)

Radiobutton(root, text="Male",padx = 5, variable=var, value=1).place(x=235,y=230)
Radiobutton(root, text="Female",padx = 20, variable=var, value=2).place(x=290,y=230)

label_4 = Label(root, text="country",width=20,font=("bold", 10))
label_4.place(x=70,y=280)

list1 = ['Philippines','Japan','Korea','China','Singapore','Hong kong'];

droplist=OptionMenu(root,c, *list1)
droplist.config(width=15)
c.set('select your country') 
droplist.place(x=240,y=280)

label_4 = Label(root, text="Programming",width=20,font=("bold", 10))
label_4.place(x=85,y=330)
var2= IntVar()
Checkbutton(root, text="java", variable=var1).place(x=235,y=330)

Checkbutton(root, text="python", variable=var2).place(x=290,y=330)

Button(root, text='Submit',width=20,bg='brown',fg='white',command=database).place(x=180,y=380)

root.mainloop()

Wednesday, March 25, 2020

Python Flask Employee Create, read, update and delete (CRUD) using pymysql and dataTables bootstrap


Python Flask Employee Create, read, update and delete (CRUD) using pymysql and dataTables bootstrap


 
#app.py
from flask import Flask, render_template, request, redirect, url_for, flash
from flaskext.mysql import MySQL
import pymysql

app = Flask(__name__)
app.secret_key = "Cairocoders-Ednalan"
 
mysql = MySQL()
  
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'testingdb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

@app.route('/')
def Index():
    conn = mysql.connect()
    cur = conn.cursor(pymysql.cursors.DictCursor)

    cur.execute('SELECT * FROM employee')
    data = cur.fetchall()
 
    cur.close()
    return render_template('index.html', employee = data)

@app.route('/add_contact', methods=['POST'])
def add_employee():
    conn = mysql.connect()
    cur = conn.cursor(pymysql.cursors.DictCursor)
    if request.method == 'POST':
        fullname = request.form['fullname']
        phone = request.form['phone']
        email = request.form['email']
        cur.execute("INSERT INTO employee (name, email, phone) VALUES (%s,%s,%s)", (fullname, email, phone))
        conn.commit()
        flash('Employee Added successfully')
        return redirect(url_for('Index'))

@app.route('/edit/', methods = ['POST', 'GET'])
def get_employee(id):
    conn = mysql.connect()
    cur = conn.cursor(pymysql.cursors.DictCursor)
 
    cur.execute('SELECT * FROM employee WHERE id = %s', (id))
    data = cur.fetchall()
    cur.close()
    print(data[0])
    return render_template('edit.html', employee = data[0])

@app.route('/update/', methods=['POST'])
def update_employee(id):
    if request.method == 'POST':
        fullname = request.form['fullname']
        phone = request.form['phone']
        email = request.form['email']
        conn = mysql.connect()
        cur = conn.cursor(pymysql.cursors.DictCursor)
        cur.execute("""
            UPDATE employee
            SET name = %s,
                email = %s,
                phone = %s
            WHERE id = %s
        """, (fullname, email, phone, id))
        flash('Employee Updated Successfully')
        conn.commit()
        return redirect(url_for('Index'))

@app.route('/delete/', methods = ['POST','GET'])
def delete_employee(id):
    conn = mysql.connect()
    cur = conn.cursor(pymysql.cursors.DictCursor)
 
    cur.execute('DELETE FROM employee WHERE id = {0}'.format(id))
    conn.commit()
    flash('Employee Removed Successfully')
    return redirect(url_for('Index'))

# starting the app
if __name__ == "__main__":
    app.run(port=3000, debug=True)
//index.html
{% extends "layout.html" %}
{% block body %}
 <div class="row"><h3>Employee</h3></div>
  <div class="row">
    <div class="col-md-4">
      {% with messages = get_flashed_messages()  %}
      {% if messages %}
      {% for message in messages %}
      <div class="alert alert-success alert-dismissible fade show" role="alert">
        {{ message }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      {% endfor %}
      {% endif %}
      {% endwith %}
      <div class="card card-body">
        <form action="{{url_for('add_employee')}}" method="POST">
          <div class="form-group">
            <input type="text" class="form-control" name="fullname" placeholder="FullName">
          </div>
          <div class="form-group">
            <input type="text" class="form-control" name="email" placeholder="Email">
          </div>
          <div class="form-group">
            <input type="text" class="form-control" name="phone" placeholder="Phone">
          </div>
          <button class="btn btn-primary btn-block">
            Save 
          </button>
        </form>
      </div>
    </div>
    <div class="col-md-8">
      <table id="example" class="table table-striped table-bordered" style="width:100%">
        <thead>
          <tr>
            <td>ID</td>
            <td>fullname</td>
            <td>email</td>
            <td>phone</td>
            <td>Action</td>
          </tr>
        </thead>
        <tbody>
          {% for data in employee %}
          <tr>
   <td>{{data.id}}</td>
            <td>{{data.name}}</td>
            <td>{{data.email}}</td>
            <td>{{data.phone}}</td>
            <td width="130">
              <a href="/edit/{{data.id}}" class="btn btn-secondary btn-sm">edit</a>
              <a href="/delete/{{data.id}}" class="btn btn-danger btn-delete btn-sm">delete</a>
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
  </div>
</div>

{% endblock %}
//layout.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Python Flask Employee Create, read, update and delete (CRUD) using pymysql</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  

<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>

  </head>
  <body>

    <!-- NAVIGATION  -->
    <nav class="navbar navbar-dark bg-dark">
      <a class="navbar-brand" href="/">Python Flask Employee Create, read, update and delete (CRUD) using pymysql and dataTables bootstrap</a>
    </nav>

    <div class="container pt-4">
      {% block body %}
      {% endblock %}
    </div>
 
<script>
const btnDelete= document.querySelectorAll('.btn-delete');
if(btnDelete) {
  const btnArray = Array.from(btnDelete);
  btnArray.forEach((btn) => {
    btn.addEventListener('click', (e) => {
      if(!confirm('Are you sure you want to delete it?')){
        e.preventDefault();
      }
    });
  })
}

$(document).ready(function() {
    $('#example').DataTable({     
      "aLengthMenu": [[3, 5, 10, 25, -1], [3, 5, 10, 25, "All"]],
        "iDisplayLength": 3
       } 
    );
} );

</script>
  </body>
</html>
//templates/edit.html
{% extends "layout.html" %}
{% block body %}

  <div class="row">
    <div class="col-md-4 offset-md-4">
      <div class="card card-body">
        <form action="/update/{{employee.id}}" method="POST">
          <div class="form-group">
            <input type="text" name="fullname" value="{{employee.name}}" class="form-control">
          </div>
          <div class="form-group">
            <input type="text" name="phone" value="{{employee.phone}}" class="form-control">
          </div>
          <div class="form-group">
            <input type="text" name="email" value="{{employee.email}}" class="form-control">
          </div>
          <div class="form-group">
            <button type="submit" class="btn btn-primary btn-block">
              Update
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>

{% endblock %}

Monday, March 23, 2020

Python Flask SQLAlchemy Search LIKE, Equals, IN, AND and OR with Pagination and Datatable bootstap


Python Flask SQLAlchemy Pagination with Search LIKE, Equals, IN, AND and OR - Datatable

LIKE: query.filter(User.name.like('%ednalan%'))
equals: query.filter(User.name == 'ednalan')
IN: query.filter(User.name.in_(['rai', 'kenshin', 'Ednalan']))
AND: query.filter(User.name == 'ednalan', User.fullname == 'clyde ednalan')
OR: from sqlalchemy import or_ 
filter(or_(User.name == 'ednalan', User.name == 'caite'))
 
#app.py
from flask import Flask, render_template, url_for, request
from flask_sqlalchemy import SQLAlchemy  
from sqlalchemy import or_
 
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
app.config['SECRET_KEY'] = 'cairocoders-ednalan'
 
db = SQLAlchemy(app) 
 
class Employees(db.Model):
 id = db.Column(db.Integer, primary_key=True)
 fullname = db.Column(db.String(150))
 position = db.Column(db.String(150))
 office = db.Column(db.String(150))
 age = db.Column(db.Integer)
 startdate = db.Column(db.String(150))
 salary = db.Column(db.String(150))
 
@app.route('/', methods=['GET', 'POST'], defaults={"page": 1}) 
@app.route('/', methods=['GET', 'POST'])
def index(page):
    page = page
    pages = 5
    #employees = Employees.query.filter().all()
    #employees = Employees.query.paginate(page,pages,error_out=False)
    employees = Employees.query.order_by(Employees.id.asc()).paginate(page,pages,error_out=False)  #desc()
    if request.method == 'POST' and 'tag' in request.form:
       tag = request.form["tag"]
       search = "%{}%".format(tag)
       #employees = Employees.query.filter(Employees.fullname.like(search)).paginate(per_page=pages, error_out=False) # LIKE: query.filter(User.name.like('%ednalan%'))
       #employees = Employees.query.filter(Employees.fullname == 'Tiger Nixon').paginate(per_page=pages, error_out=True) # equals: query.filter(User.name == 'ednalan')    
       #employees = Employees.query.filter(Employees.fullname.in_(['rai', 'kenshin', 'Ednalan'])).paginate(per_page=pages, error_out=True) # IN: query.filter(User.name.in_(['rai', 'kenshin', 'Ednalan']))  
       #employees = Employees.query.filter(Employees.fullname == 'Tiger Nixon', Employees.position == 'System Architect').paginate(per_page=pages, error_out=True) # AND: query.filter(User.name == 'ednalan', User.fullname == 'clyde ednalan')    
       employees = Employees.query.filter(or_(Employees.fullname == 'Tiger Nixon', Employees.fullname == 'Ednalan')).paginate(per_page=pages, error_out=True) # OR: from sqlalchemy import or_  filter(or_(User.name == 'ednalan', User.name == 'caite'))
       return render_template('index.html', employees=employees, tag=tag)
    return render_template('index.html', employees=employees)
  
if __name__ == '__main__':
    app.run(debug=True)
//templates/index.html
<html>
<head>
<title>Python Flask SQLAlchemy Pagination with Search LIKE, Equals, IN, AND and OR - Datatable</title>  
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>   
</head>
<body>
<div class="container">
 <p><h2>Python Flask SQLAlchemy Pagination with Search LIKE, Equals, IN, AND and OR - Datatable</h2>  </p>
 <div class="row">
  <div class="col-8">
  <strong>Search For : {{ tag}}</strong>
  </div>
  <div class="col-4">
   <form action="" method="post" autocomplete="off"> 
   <div class="row">
    <div class="col-6">
    <input type="text" class="form-control" name="tag" id="tag"  placeholder="Enter keyword"/> 
    </div>
    <div class="col-6" align="left">
    <input type="submit" value="Search" class="form-control btn btn-primary " name=""> 
    </div>
   </form> 
   </div>
  </div>
 </div> 
<div class="row">
<div class="col-12">
  <table id="example" class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr>
                <th><input type="checkbox" onclick="checkAll(this)"></th>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
  {% for employee in employees.items %}
  <tr>
                <td><input type="checkbox" name="">{{ employee.id}}</td>
                <td>{{ employee.fullname}}</td>
                <td>{{ employee.position}}</td>
                <td>{{ employee.office}}</td>
                <td>{{ employee.age}}</td>
                <td>{{ employee.startdate}}</td>
                <td>{{ employee.salary}}</td>
        </tr>
        {% endfor %}  
        </tbody>
        <tfoot>
            <tr>
                <th></th>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
  </table>
   <nav aria-label="Page navigation example">
                <ul class="pagination">
                    {% if employees.has_prev %}
                      <li class="page-item"> <a class="page-link" href="{{ url_for('index', page=employees.prev_num) }}">Previous</a></li>
                    {% else %}
                      <li class="page-item"><a class="page-link btn disabled" href="#">Previous</a></li>
                    {% endif %}
     
     {% for page in employees.iter_pages(left_edge=3, right_edge=3) %}
     {% if page %}
     
      {% if page==employees.page %}
       <li class="page-item active"><a class="page-link" href="{{ url_for('index', page=page) }}">{{ page }}</a></li>
      {% else %}
       <li class="page-item"><a class="page-link" href="{{ url_for('index', page=page) }}">{{ page }}</a></li>
      {% endif %}
      
     {% else %}
      <li class="page-item disabled" id="example_ellipsis"><a href="#" class="page-link">…</a></li> 
     {% endif %}
     {% endfor %}

                    {% if employees.has_next %}
                      <li class="page-item"> <a class="page-link" href="{{ url_for('index', page=employees.next_num) }}">Next</a></li>
                    {% else %}
                      <li class="page-item"><a class="page-link btn disabled" href="#">Next</a></li>
                    {% endif %}

                </ul>
    </nav>
 </div>
 </div>

</div> 
<style>
table{
    width:100%;
}
#example_filter{
    float:right;
}
#example_paginate{
    float:right;
}
label {
    display: inline-flex;
    margin-bottom: .5rem;
    margin-top: .5rem;
    
}
.page-item.disabled .page-link {
    color: #6c757d;
    pointer-events: none;
    cursor: auto;
    background-color: #fff;
    border-color: #dee2e6;
}
</style>
<script>
function checkAll(bx) {
  var cbs = document.getElementsByTagName('input');
  for(var i=0; i < cbs.length; i++) {
    if(cbs[i].type == 'checkbox') {
      cbs[i].checked = bx.checked;
    }
  }
}
</script>
</body>
</html>

Sunday, March 22, 2020

Python Flask SQLAlchemy Pagination - Datatable bootstap


Python Flask SQLAlchemy Pagination - Datatable bootstap

 
#app.py
from flask import Flask, render_template, flash, redirect, url_for, request
from flask_sqlalchemy import SQLAlchemy  

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db' 
app.config['SECRET_KEY'] = 'cairocoders-ednalan'

db = SQLAlchemy(app) 

class Employees(db.Model):
 id = db.Column(db.Integer, primary_key=True)
 fullname = db.Column(db.String(150))
 position = db.Column(db.String(150))
 office = db.Column(db.String(150))
 age = db.Column(db.Integer)
 startdate = db.Column(db.String(150))
 salary = db.Column(db.String(150))
 
@app.route('/employees/')
def employees(page_num):
    employees = Employees.query.paginate(per_page=5, page=page_num, error_out=True)
    return render_template('index.html', employees=employees)
 
if __name__ == '__main__':
    app.run(debug=True)
//index.hmtl
<html>
<head>
<title>Python Flask SQLAlchemy Pagination</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>   
</head>
<body>
<div class="container">
 <div class="row">
 <p><h2>Python Flask SQLAlchemy Pagination - Datatable bootstap</h2>  </p>
 <table id="example" class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr>
                <th><input type="checkbox" onclick="checkAll(this)"></th>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
   {% for employee in employees.items %}
   <tr>
                <td><input type="checkbox" name=""></td>
                <td>{{ employee.fullname}}</td>
                <td>{{ employee.position}}</td>
                <td>{{ employee.office}}</td>
                <td>{{ employee.age}}</td>
                <td>{{ employee.startdate}}</td>
                <td>{{ employee.salary}}</td>
            </tr>
            {% endfor %}
        </tbody>
        <tfoot>
            <tr>
                <th></th>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
    </table>
 </div>
 
   <ul class="pagination">
  {% if employees.has_prev %}
   <li class="page-item"><a class="page-link" href="{{ url_for('employees', page_num=employees.prev_num) }}">Previous</a></li>
  {% else %}
   <li class="page-item disabled"><span class="page-link">Previous</span>
  {% endif %}
   </li>
   
  {% for page in employees.iter_pages(left_edge=3, right_edge=3) %}
  {% if page %}
   <li class="page-item"><a class="page-link" href="{{ url_for('employees', page_num=page) }}">{{ page }}</a></li>
  {% else %}
   <li class="page-item disabled" id="example_ellipsis"><a href="#" class="page-link">…</a></li> 
  {% endif %}
  {% endfor %}
 
  {% if employees.has_next %}
   <li class="page-item"><a class="page-link" href="{{ url_for('employees', page_num=employees.next_num) }}">Next</a></li>
  {% else %}
   <li class="page-item disabled"><span class="page-link">Next</span>
  {% endif %}
   </ul>

 
</div>
<style>
table{
    width:100%;
}
#example_filter{
    float:right;
}
#example_paginate{
    float:right;
}
label {
    display: inline-flex;
    margin-bottom: .5rem;
    margin-top: .5rem;
   
}
.page-item.disabled .page-link {
    color: #6c757d;
    pointer-events: none;
    cursor: auto;
    background-color: #fff;
    border-color: #dee2e6;
}
</style>
<script>
function checkAll(bx) {
  var cbs = document.getElementsByTagName('input');
  for(var i=0; i < cbs.length; i++) {
    if(cbs[i].type == 'checkbox') {
      cbs[i].checked = bx.checked;
    }
  }
}
</script>  
</body>
</html>

Saturday, March 21, 2020

Flask Tutorial User Profile, Error Handling, Add Post and Pagination - Part 2


Flask Tutorial User Profile, Error Handling, Add Post and Pagination - Part 2

Part 1 Tutorial

#app.py
from flask import Flask, render_template, flash, redirect, url_for, request
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField
from wtforms.validators import DataRequired, ValidationError, Email, EqualTo, Length
from flask_sqlalchemy import SQLAlchemy  
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import LoginManager, UserMixin, current_user, login_user, logout_user, login_required
import os

path = "/"
PEOPLE_FOLDER = os.path.join(path,'static', 'img')

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db' 
app.config['SECRET_KEY'] = 'cairocoders-ednalan'

app.config['UPLOAD_FOLDER'] = PEOPLE_FOLDER

login = LoginManager(app)
login.login_view = 'login'

db = SQLAlchemy(app) 

followers = db.Table(
    'followers',
    db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('Remember Me')
    submit = SubmitField('Sign In')
 
class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    password2 = PasswordField(
        'Repeat Password', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Register')

    def validate_username(self, username):
        user = User.query.filter_by(username=username.data).first()
        if user is not None:
            raise ValidationError('Please use a different username.')

    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user is not None:
            raise ValidationError('Please use a different email address.') 

class EditProfileForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    about_me = TextAreaField('About me', validators=[Length(min=0, max=140)])
    submit = SubmitField('Submit')
 
    def __init__(self, original_username, *args, **kwargs):
        super(EditProfileForm, self).__init__(*args, **kwargs)
        self.original_username = original_username

    def validate_username(self, username):
        if username.data != self.original_username:
            user = User.query.filter_by(username=self.username.data).first()
            if user is not None:
                raise ValidationError('Please use a different username.')
    
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    about_me = db.Column(db.String(140))
    last_seen = db.Column(db.DateTime, default=datetime.utcnow)
    profile_pic = db.Column(db.String(150))
    #profile_pic = 'mypics.jpg'
  
    def __repr__(self):
        return ''.format(self.username)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def avatar(self, profilepic):
        profilepic = os.path.join(app.config['UPLOAD_FOLDER'], self.profile_pic)
        return profilepic
  
    def followed_posts(self):
        followed = Post.query.join(
            followers, (followers.c.followed_id == Post.user_id)).filter(
                followers.c.follower_id == self.id)
        own = Post.query.filter_by(user_id=self.id)
        return followed.union(own).order_by(Post.timestamp.desc())
  
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    def __repr__(self):
        return ''.format(self.body)
  
class PostForm(FlaskForm):
    post = TextAreaField('Say something', validators=[DataRequired()])
    submit = SubmitField('Submit')

 
@login.user_loader
def load_user(id):
    return User.query.get(int(id))

@app.before_request
def before_request():
    if current_user.is_authenticated:
        current_user.last_seen = datetime.utcnow()
        db.session.commit()

@app.errorhandler(404) #404 page not found 500 internal server error
def not_found_error(error):
    return render_template('404.html'), 404
 
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
@login_required
def index():
    #user_post = {'username': 'cairocoders'}
    #hash = generate_password_hash('test1')
    #check_hash = check_password_hash(hash, 'test1')
 
    form = PostForm()
    if form.validate_on_submit():
        post = Post(body=form.post.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your post is now live!')
        return redirect(url_for('index'))

    #posts = current_user.followed_posts().all()
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(page, 5, False) #POSTS_PER_PAGE = 5
    next_url = url_for('index', page=posts.next_num) \
        if posts.has_next else None
    prev_url = url_for('index', page=posts.prev_num) \
        if posts.has_prev else None
    return render_template('index.html', title='Home', form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)
         
    #return render_template('index.html', title='Home', user_post=user_post, posts=posts, hash=hash, check_hash=check_hash)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        return redirect(url_for('index'))
    return render_template('login.html', title='Sign In', form=form)

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))

@app.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('Congratulations, you are now a registered user!')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)

@app.route('/user/')
@login_required
def user(username):
    user = User.query.filter_by(username=username).first_or_404()
    page = request.args.get('page', 1, type=int)
    posts = user.posts.order_by(Post.timestamp.desc()).paginate(page, 5, False)
    next_url = url_for('user', username=user.username, page=posts.next_num) \
        if posts.has_next else None
    prev_url = url_for('user', username=user.username, page=posts.prev_num) \
        if posts.has_prev else None
    return render_template('user.html', user=user, posts=posts.items, next_url=next_url, prev_url=prev_url)

@app.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfileForm(current_user.username)
    if form.validate_on_submit():
        current_user.username = form.username.data
        current_user.about_me = form.about_me.data
        db.session.commit()
        flash('Your changes have been saved.')
        return redirect(url_for('edit_profile'))
    elif request.method == 'GET':
        form.username.data = current_user.username
        form.about_me.data = current_user.about_me
    return render_template('edit_profile.html', title='Edit Profile', form=form)
 
@app.route('/explore')
@login_required
def explore():
    page = request.args.get('page', 1, type=int)
    posts = Post.query.order_by(Post.timestamp.desc()).paginate(page, 5, False)
    next_url = url_for('explore', page=posts.next_num) \
        if posts.has_next else None
    prev_url = url_for('explore', page=posts.prev_num) \
        if posts.has_prev else None
    return render_template('index.html', title='Explore', posts=posts.items, next_url=next_url, prev_url=prev_url)
         
if __name__ == '__main__':
    app.run(debug=True)
//templates/index.html
{% extends "base.html" %}

{% block content %}
<div class="row">
    <!--<p>hash, {{ hash }}!</p>
    <p>Check hash, {{ check_hash }}</p> -->
    <h1>Hi, {{ current_user.username }}!</h1>
    {% if form %}
    <form action="" method="post">
        {{ form.hidden_tag() }}
        <p>
            {{ form.post.label }}<br>
            {{ form.post(cols=32, rows=4, class_="form-control") }}<br>
            {% for error in form.post.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>{{ form.submit() }}</p>
    </form>
    {% endif %}
 
    {% for post in posts %}
        {% include '_post.html' %}
    {% endfor %}
 
 <p style="padding-bottom:50px;">
    {% if prev_url %}
    <a href="{{ prev_url }}" class="btn btn-primary">Newer posts</a>
    {% endif %}
    {% if next_url %}
    <a href="{{ next_url }}" class="btn btn-primary">Older posts</a>
    {% endif %}
 <br/>
 </p>
</div> 
{% endblock %}
//templates/base.html
<html>
    <head>
      {% if title %}
      <title>{{ title }} - blog</title>
      {% else %}
      <title>Welcome to blog</title>
      {% endif %}
<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>     
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">Cairocoders Blog</a>
    </div>
    <ul class="nav navbar-nav">
      <li class="active"><a href="{{ url_for('index') }}">Home</a></li>
      <li><a href="{{ url_for('explore') }}">Post</a></li>
      <li><a href="#">About Us</a></li>
      <li><a href="#">Contact Us</a></li>
    </ul>
 {% if current_user.is_anonymous %}
    <ul class="nav navbar-nav navbar-right">
      <li><a href="{{ url_for('login') }}"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
    </ul>
 {% else %}
 <ul class="nav navbar-nav navbar-right">
      <li><a href="{{ url_for('user', username=current_user.username) }}"> Profile</a></li>
  <li><a href="{{ url_for('logout') }}"> Logout</a></li>
 </ul>
 {% endif %}
  </div>
</nav>

<div class="container">
<p>Flask Tutorial User Profile, Error Handling, Add Post and Pagination - Part 2</p>  
        {% with messages = get_flashed_messages() %}
        {% if messages %}
        <ul>
            {% for message in messages %}
            <li>{{ message }}</li>
            {% endfor %}
        </ul>
        {% endif %}
        {% endwith %}
  
        {% block content %}{% endblock %}
</div>  
</body>
</html>
//templates/login.html
{% extends "base.html" %}

{% block content %}
    <h1>Sign In</h1>
    <form action="" method="post" novalidate>
        {{ form.hidden_tag() }}
        <p>
            {{ form.username.label }}<br>
            {{ form.username(size=32, class_="form-control") }}<br>
            {% for error in form.username.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>
            {{ form.password.label }}<br>
            {{ form.password(size=32, class_="form-control") }}<br>
            {% for error in form.password.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>{{ form.remember_me() }} {{ form.remember_me.label }}</p>
        <p>{{ form.submit() }}</p>
    </form>
    <p>New User? <a href="{{ url_for('register') }}">Click to Register!</a></p>
{% endblock %}
//templates/register.html
{% extends "base.html" %}

{% block content %}
    <h1>Register</h1>
    <form action="" method="post">
        {{ form.hidden_tag() }}
        <p>
            {{ form.username.label }}<br>
            {{ form.username(size=32, class_="form-control") }}<br>
            {% for error in form.username.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>
            {{ form.email.label }}<br>
            {{ form.email(size=64, class_="form-control") }}<br>
            {% for error in form.email.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>
            {{ form.password.label }}<br>
            {{ form.password(size=32, class_="form-control") }}<br>
            {% for error in form.password.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>
            {{ form.password2.label }}<br>
            {{ form.password2(size=32, class_="form-control") }}<br>
            {% for error in form.password2.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>{{ form.submit(class_="btn btn-primary") }}</p>
    </form>
{% endblock %}
//user.html
{% extends "base.html" %}

{% block content %}
    <table>
        <tr valign="top">
            <td><img src="{{ user.avatar(profilepic) }}" width="128"></td>
            <td style="padding-left:10px;">
                <h1>User: {{ user.username }}</h1>
                {% if user.about_me %}<p>{{ user.about_me }}</p>{% endif %}
                {% if user.last_seen %}<p>Last seen on: {{ user.last_seen }}</p>{% endif %}
                {% if user == current_user %}
                <p><a href="{{ url_for('edit_profile') }}">Edit your profile</a></p>
                {% endif %}
            </td>
        </tr>
    </table>
    <hr>
    {% for post in posts %}
        {% include '_post.html' %}
    {% endfor %}
{% endblock %}
//templates/_post.html
<table class="table table-hover">
        <tr valign="top">
            <td width="36"><img src="{{ post.author.avatar(profilepics) }}" width="50"></td>
   <td align="left"><a href="{{ url_for('user', username=post.author.username) }}">{{ post.author.username }}</a> says:<br>{{ post.body }}</td>
        </tr>
    </table>
//templates/includes/_formhelpers.html
{% macro render_field(field) %}
  {{ field.label }}
  {{ field(**kwargs)|safe }}
  {% if field.errors %}
    {% for error in field.errors %}
      <span class="help-inline">{{ error }}</span>
    {% endfor %}
  {% endif %}
{% endmacro %}
//templates/404.html
{% extends "base.html" %}

{% block content %}
    <h1>File Not Found</h1>
    <p><a href="{{ url_for('index') }}">Back</a></p>
{% endblock %}

Wednesday, March 4, 2020

How to Import Custom Python Packages on AWS Lambda Function


How to Import Custom Python Packages on AWS Lambda Function


In this tutorial I will show how to install the pymysql import pymysql on AWS Lambda Function

1. Open powershell
2. Make a directory  = mkdir pythonimport
3. Change directory = chdir pythonimport
4. Make and activate a virtual environment
5. Type this command to activate virtual environment : virtualenv.exe venv
6. Change to the "venv" directory. Type this command: cd venv
7. Activate the virtual environment. Type this command:  .\Scripts\activate

8. install package pip install pymysql

Monday, March 2, 2020

Flask Tutorial templates, webforms, database and user logins - Part 1


Flask Tutorial templates, webforms, database and user logins - Part 1

In this tutorial, you are going to learn how to set up a Flask project.
By the end of this chapter part 1 you are going to have a simple Flask web application login system

below is a list.
1. Templates
how to work with templates
2. Web Forms
how to work with web forms
To handle the web forms in this application we will use the Flask-WTF extension
install Flask-WTF in your virtual environment:
(venv) $ pip install flask-wtf
3. Database
how to work with databases.
To install Flask-SQLAlchemy in your virtual environment, make sure you have activated it first, and then run:
(venv) $ pip install flask-sqlalchemy
4. User Logins
how to create a user login subsystem
install Flask-Login in your virtual environment:

(venv) $ pip install flask-login


 
#app.py
from flask import Flask, render_template, flash, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired
from flask_sqlalchemy import SQLAlchemy  
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import LoginManager, UserMixin, current_user, login_user, logout_user, login_required

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db' 
app.config['SECRET_KEY'] = 'cairocoders-ednalan'

login = LoginManager(app)
login.login_view = 'login'

db = SQLAlchemy(app) 

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('Remember Me')
    submit = SubmitField('Sign In')
 
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))

    def __repr__(self):
        return ''.format(self.username)  
  
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
  
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    def __repr__(self):
        return ''.format(self.body)
 
@login.user_loader
def load_user(id):
    return User.query.get(int(id))
 
@app.route('/')
@app.route('/index')
@login_required
def index():
    user_post = {'username': 'cairocoders'}
    hash = generate_password_hash('test1')
    check_hash = check_password_hash(hash, 'test1')
    posts = [
        {
            'author': {'username': 'tutorial1'},
            'body': 'Beautiful day in Olongapo City!'
        },
        {
            'author': {'username': 'turorial10'},
            'body': 'Flask is a lightweight WSGI web application framework.!'
        }
    ]
    return render_template('index.html', title='Home', user_post=user_post, posts=posts, hash=hash, check_hash=check_hash)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        return redirect(url_for('index'))
    return render_template('login.html', title='Sign In', form=form)

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))
 
if __name__ == '__main__':
    app.run(debug=True)
//templates/index.html
{% extends "base.html" %}

{% block content %}
    <p>hash, {{ hash }}!</p>
    <p>Check hash, {{ check_hash }}</p>
    <h1>Hi, {{ current_user.username }}!</h1>
    {% for post in posts %}
    <div><p>{{ post.author.username }} says: <b>{{ post.body }}</b></p></div>
    {% endfor %}
{% endblock %}
//templates/base.html
<html>
    <head>
      {% if title %}
      <title>{{ title }} - blog</title>
      {% else %}
      <title>Welcome to blog</title>
      {% endif %}
</head>
<body>
<div>
    Blog:
    <a href="{{ url_for('index') }}">Home</a>
    {% if current_user.is_anonymous %}
    <a href="{{ url_for('login') }}">Login</a>
    {% else %}
    <a href="{{ url_for('logout') }}">Logout</a>
    {% endif %}
</div>
        <hr>
<p>Flask Tutorial templates, webforms, database and user logins - Part 1</p>  
        {% with messages = get_flashed_messages() %}
        {% if messages %}
        <ul>
            {% for message in messages %}
            <li>{{ message }}</li>
            {% endfor %}
        </ul>
        {% endif %}
        {% endwith %}
  
        {% block content %}{% endblock %}
</body>
</html>
//templates/login.html
{% extends "base.html" %}

{% block content %}
    <h1>Sign In</h1>
    <form action="" method="post" novalidate>
        {{ form.hidden_tag() }}
        <p>
            {{ form.username.label }}<br>
            {{ form.username(size=32) }}<br>
            {% for error in form.username.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>
            {{ form.password.label }}<br>
            {{ form.password(size=32) }}<br>
            {% for error in form.password.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>{{ form.remember_me() }} {{ form.remember_me.label }}</p>
        <p>{{ form.submit() }}</p>
    </form>
{% endblock %}

Related Post