Home > Courses > Flask: Python Web Development > Update and delete a record with Flask

Update and delete a record with Flask

Subject: Flask: Python Web Development
In this topic I will share with you the full code on how I introduced the edit and delete to the students record we had in the last topic.

Full code
Here we have the full code of all the files we have modified.

Student Blueprint
student_blueprint.py

from flask import Blueprint, render_template, request, url_for, redirect
import re 
import sqlite3 

from database import connect_db
conn = connect_db()

student_bp=Blueprint("student_blueprint", __name__, static_folder="static", template_folder="templates")

#load form
@student_bp.route('/student', methods =['GET']) 
def student():
  args = request.args
  msg=''
  if 'task' in args: #check if in edit mode    
    sel_id = args.get('value')  

    cursor = conn.cursor() 
    cursor.execute('SELECT * FROM student WHERE id = "'+sel_id+'"')  
    data_preview = cursor.fetchone()            
    msg="Edit"
    return render_template('student.html', preview=data_preview)
  else: # else load add mode      
	  return render_template('student.html')

#display record
@student_bp.route('/seestudents') 
def seestudents():	 

  cursor = conn.cursor()  
  cursor.execute('SELECT * FROM student')
  data = cursor.fetchall()

  return render_template('seestudents.html', students=data)
	 
#process the student add
@student_bp.route('/addstudent', methods=['GET', 'POST']) 
def addstudent(): 
  if request.method == 'POST': 
    surname = request.form['surname'] 
    othernames = request.form['othernames'] 
    address = request.form['address']  

    if "edit_id" in request.form: # Edit Record
      edit_id = request.form['edit_id'] 
      conn.execute('UPDATE student SET surname_name="'+surname+'", other_name="'+othernames+'", address_address="'+address+'" WHERE id = "'+edit_id+'"')              
      conn.commit()
        
      return redirect('student?task=edit&value='+edit_id+'&done=1')

    else: #Add  Record 
      conn.execute('INSERT INTO student (surname_name,other_name,address_address) VALUES (?,?,?)',(surname, othernames, address)) 
      conn.commit() 
    
      output="Student record saved"
      return render_template('student.html', msg=output) 


@student_bp.route('/delete_student', methods =['GET'])
def delete():
    args = request.args
    sel_id = args.get('value')
   
   
    conn.execute('DELETE FROM student WHERE id = "'+sel_id+'"')              
    conn.commit()
    
    #returning back to seestudents 
    return redirect(url_for('student_blueprint.seestudents'))  


App.py
Here is the full code of app.py

app.py

from flask import Flask, render_template, request
import re 

from database import connect_db
conn = connect_db()

from student_blueprint import student_bp
from table_create_blueprint import tables_bp

app = Flask(__name__) 
app.secret_key = 'your secret key'

#register or access the blueprints
app.register_blueprint(student_bp)
app.register_blueprint(tables_bp)

#load the home or index page
@app.route('/home') 
@app.route('/') 
def home(): 
  return render_template('index.html') 

if __name__ == '__main__': 
       app.run(debug=True)    


Layout template file
templates/layout.htm

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
School Grading System - {% block title %}{% endblock title %}
</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>

    <header>
<h1>School Grading System</h1>
    </header>

    <nav>
        <a href="{{ url_for('home') }}">Home</a>        
        <a href="{{ url_for('student_blueprint.seestudents') }}">Students</a>
        <a href="#">Subjects</a>              
        <a href="#">Grades</a>
    </nav>
 
    <div class="container">
   <h2> {% block subheading %}{% endblock subheading %}</h2>

{% block content %}
<p>No messages.</p>
{% endblock content %}
    </div>
<footer>
Designed and Developed by Ben Onuorah
</footer>
</body>
</html>


Student record display file
With column for edit and delete links

templates/seestudents.html

<!DOCTYPE html>
{% extends 'layout.html' %}

{% block title %}See Students{% endblock title %}
<h2>
{% block subheading %}See Students{% endblock subheading %}</h2>
{% block content %}

<p align='center'>
  <a href="{{ url_for('student_blueprint.student') }}">Add New Record</a>  
</p>

<table width="100%" border=1> 
            <tr> 
              <th>Id</th> 
              <th>Surname</th> 
              <th>Othernames</th> 
              <th>Address</th>
              <th>Edit</th>
              <th>Delete</th>
            </tr> 

            {%for rec in students%} 
               <tr> 
                 <td>{{rec[0]}}</td> 
                 <td>{{rec[1]}}</td> 
                 <td>{{rec[2]}}</td> 
                 <td>{{rec[3]}}</td> 
                 <td>
                    <a href="delete_student?value={{rec[0]}}" title="Delete" onclick="return confirm('Are you sure you want to delete?')">
                      Delete
                    </a>
                 </td> 
                 <td>                   
                    <a href="student?task=edit&value={{rec[0]}}" title="Edit">
                      Edit
                    </a>
                 </td> 
              </tr> 
            {%endfor%} 
          </table>   

{% endblock content %}


Student entry form file
templates/student.htm

<!DOCTYPE html>
{% extends 'layout.html' %}
{% block title %}Student{% endblock title %}
<h2>

{% block subheading %}

  {% if request.args.get('task') == 'edit' %} 
    Edit Student
  {% else %}
    Add Student
  {% endif %}

{% endblock subheading %}
</h2>

{% block content %}

<p align='center'>
  <a href="{{ url_for('student_blueprint.seestudents') }}">See Record</a>  
</p>

{% if msg %}
  <p><b>{{ msg }}</b></p>
{% elif request.args.get('done')  %}  
  <p><b>Edited</b></p>
{% endif %}
    <form method="POST" action ="{{ url_for('student_blueprint.addstudent') }}">
      Surname: <br/>
      {% if preview is defined %}
          <input type="text" name="surname" value="{{ preview[1] }}" />
      {% else %}
          <input type="text" name="surname" />
      {% endif %}
        
      <br/>
      
      Other names: <br/>
      {% if preview is defined %}
          <input type="text" name="othernames" value="{{ preview[2] }}" />
      {% else %}
          <input type="text" name="othernames" />
      {% endif %}     
      <br/>
      
      Address: <br/>
      <textarea name="address">{% if preview is defined %}{{ preview[3] }}{% endif %}</textarea>
      
      {% if preview is defined %}
        <input type = "hidden" name = "edit_id" value="{{ preview[0] }}" />
      {% endif %}

      <br/>
      <input type="submit" name="save" value="Save"/>
  </form>

{% endblock content %}


Record with Edit and Delete columns




Editing "John" record




Notice the URL




Update now completed (Edited to Johnson)




Delete "Femi's" record




Record deleted





By: Benjamin Onuorah

Comments

No Comment yet!

Login to comment or ask question on this topic


Previous Topic Next Topic

Supported by