tutorial101 is the one place for high quality web development, Web Design and software development tutorials and Resources programming. Learn cutting edge techniques in web development, design and software development, download source components and participate in the community.
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})
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})
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
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
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)
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
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)