article

Friday, May 13, 2022

Laravel Join Two Tables

Laravel Join Two Tables

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory. 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Create tables
php artisan make:migration create_categories_table
php artisan make:migration create_products_table
C:\xampp\htdocs\laravel9\blog>php artisan make:migration create_categories_table
C:\xampp\htdocs\laravel9\blog>php artisan make:migration create_products_table

Open new products and categories migrations
yourproject/database/migrations
blog\database\migrations\_create_products_table.php
edit code blog\database\migrations\_create_products_table.php
products_table.php
//products_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('prodname');
            $table->integer('category_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
};
categories_table.php
//categories_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('catname');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table

CREATE TABLE `products` (
`id` bigint(20) UNSIGNED NOT NULL,
`prodname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`category_id` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `products` (`id`, `prodname`, `category_id`, `created_at`, `updated_at`) VALUES
(1, 'Milk', 1, '2022-05-13 07:43:06', '2022-05-13 07:43:06'),
(2, 'Coffee', 1, '2022-05-13 07:43:06', '2022-05-13 07:43:06'),
(3, 'Iphone 13', 2, '2022-05-13 07:43:58', '2022-05-13 07:43:58'),
(4, 'Samsung Galaxy', 2, '2022-05-13 07:43:58', '2022-05-13 07:43:58');

CREATE TABLE `categories` (
`id` bigint(20) UNSIGNED NOT NULL,
`catname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `categories` (`id`, `catname`, `created_at`, `updated_at`) VALUES
(1, 'Drink', '2022-05-13 07:42:02', '2022-05-13 07:42:02'),
(2, 'Mobiles', '2022-05-13 07:42:02', '2022-05-13 07:42:02');
Creating Controller

php artisan make:controller ProductController --resource
C:\xampp\htdocs\laravel9\blog>php artisan make:controller ProductController --resource
change it with the following codes:
blog\app\Http\Controllers\ProductController.php
//blog\app\Http\Controllers\ProductController.php
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Product;

class ProductController extends Controller
{
    public function index()
    {
        $products = Product::with('category')->get();
        $categories = Category::with('products')->get();
        
        return view('index', compact('products', 'categories'));
    }
}
Create Model

Model is used to get the data from the database.

php artisan make:model Product
php artisan make:model Category

C:\xampp\htdocs\laravel9\blog>php artisan make:model Product
C:\xampp\htdocs\laravel9\blog>php artisan make:model Category

blog\app\Models\Category.php and blog\app\Models\Product.php

blog\app\Models\Category.php
//blog\app\Models\Category.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Product;

class Category extends Model
{
    use HasFactory;
    protected $fillable = [
        'id',
        'catname',
    ];
 
    public function products()
    {
        return $this->hasMany(Product::class, 'category_id', 'id');
    }
}
blog\app\Models\Product.php
//blog\app\Models\Product.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Category;

class Product extends Model
{
    use HasFactory;
    protected $fillable = [
        'id',
        'prodname',
        'category_id',
    ];
 
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}
Create Views

Bootstrap 5 https://getbootstrap.com/docs/5.1/getting-started/download/
blog\resources\views\layout.blade.php
//blog\resources\views\layout.blade.php
<html>
<head>
    <title>Laravel 9 Join Two Tables</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<div class="container">
    @yield('content')
</div>
</body>
</html>
blog\resources\views\index.blade.php
//blog\resources\views\index.blade.php
@extends('layout')

@section('content')
<div class="row" style="margin:20px;">
    <div class="col-12">
    <h2>Laravel Join Two Tables</h2>
    <table class="table table-bordered table-striped">
        <thead>
            <tr>
            <th scope="col">#</th>
            <th scope="col">Product name</th>
            <th scope="col">Category Name</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($products as $product)
            <tr>
                <td>{{ $loop->iteration }}</td>
                <td>{{ $product->prodname }}</td>
                <td>{{ $product->category->catname }}</td>
            </tr>
            @endforeach
        </tbody>
        </table>
    </div>
</div>    
Creating Routes
blog\routes\web.php
//blog\routes\web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController; //add product Controller

Route::get('/', function () {
    return view('welcome');
});

Route::get('products', [ProductController::class, 'index']);
Run C:\xampp\htdocs\laravel\blog>php artisan serve

Starting Laravel development server: http://127.0.0.1:8000

Wednesday, May 11, 2022

Django Mysql Insert Data Using Jquery Ajax

Django Mysql Insert Data Using Jquery Ajax

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js

Register App myapp and
Connect to MySQL Database

devproject/settings.py
 
//devproject/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]
    
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}
Create Model
 
//myapp/models.py
from django.db import models
 
# Create your models here.
class Member(models.Model):
    firstname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)
    address = models.CharField(max_length=50)
    username = models.CharField(max_length=50)
  
    class Meta:  
        db_table = "blog_member"
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\devproject>python manage.py makemigrations
C:\django\devproject>python manage.py migrate

Creating View
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render, redirect
from myapp.models import Member
 
# Create your views here.
def index(request):
    members = Member.objects.all()
    return render(request, 'index.html', {'members': members})
 
def insert(request):
    member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'], address=request.POST['address'], username=request.POST['username'])
    member.save()
    return redirect('/')
Template myapp/templates/index.html
 
//myapp/templates/index.html
{% extends 'base.html' %}
{% block body %}

    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addnew">
      Add New
    </button>

    <!-- Modal -->
    <div class="modal fade" id="addnew" tabindex="-1" aria-labelledby="addnewLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="addnewLabel">New Member</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <form class="" method="post">
              {% csrf_token %}
              <div class="form-inline">
                  <label>UserName</label>
                  <input type="text" id="username" name="username" class="form-control"/>
              </div>
              <div class="form-inline">
                  <label>Firstname</label>
                  <input type="text" id="firstname" name="firstname" class="form-control"/>
                  <label>Lastname</label>
                  <input type="text" id="lastname" name="lastname" class="form-control"/>
              </div>
              <div class="form-group">
                  <label>Address</label>
                  <input type="text" id="address" name="address" class="form-control"/>
              </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary" id="submit">Submit</button>
          </form>
          </div>
        </div>
      </div>
    </div>

    <hr style="border-top:1px solid #000; clear:both;"/>
    <table class="table table-bordered">
        <thead class="alert-warning">
            <tr>
                <th>Firstname</th>
                <th>Lastname</th>
                <th>Address</th>
            </tr>
        </thead>
        <tbody>
            {% for member in members %}
            <tr>
                <td>{{ member.firstname }}</td>
                <td>{{ member.lastname }}</td>
                <td>{{ member.address  }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
{% endblock %}
myapp/templates/base.html
//myapp/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
{% load static %}
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="{% static 'js/script.js' %}"></script>
</head>
<body>
  <div class="container">
  <header>
    <h1>Django Mysql Insert Data Using Jquery Ajax</h1>
  </header>
  <hr>
  <main>
    {% block body %}
    {% endblock %}
  </main>
  <hr>
  </div>
</body>
</html>
myapp/static/js/script.js
//myapp/static/js/script.js
$(document).ready(function(){
    $('#submit').on('click', function(){
        $firstname = $('#firstname').val();
        $lastname = $('#lastname').val();
        $address = $('#address').val();
        $username = $('#username').val();
  
        if($firstname == "" || $lastname == "" || $address == "" || $username == ""){
            alert("Please complete field");
        }else{
            $.ajax({
                type: "POST",
                url: "insert/",
                data:{
                    firstname: $firstname,
                    lastname: $lastname,
                    address: $address,
                    username: $username,
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
                },
                success: function(){
                    alert('Save Data');
                    $('#firstname').val('');
                    $('#lastname').val('');
                    $('#address').val('');
                    $('#username').val('');
                    window.location = "/";
                }
            });
        }
    });
});
URL
devproject/urls.py
//devproject/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
    path('insert/',views.insert, name='insert'),
]
Run : C:\django\devproject>python manage.py runserver

Sunday, May 8, 2022

Laravel 9 CRUD (Create, Read, Update and Delete)

Laravel 9 CRUD (Create, Read, Update and Delete)

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory. 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Create the tables
php artisan make:migration create_students_table
C:\xampp\htdocs\laravel9\blog>php artisan make:migration create_students_table

Open new students migrations
yourproject/database/migrations
blog\database\migrations\_create_students_table.php
edit code blog\database\migrations\_create_students_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->string("address");
            $table->string("mobile");
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table

Creating Controller

php artisan make:controller StudentController --resource
C:\xampp\htdocs\laravel9\blog>php artisan make:controller StudentController --resource
change it with the following codes:
blog\app\Http\Controllers\StudentController.php
//blog\app\Http\Controllers\StudentController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Student; //add Student Model - Data is coming from the database via Model.

class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $students = Student::all();
        return view ('students.index')->with('students', $students);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('students.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->all();
        Student::create($input);
        return redirect('student')->with('flash_message', 'Student Addedd!');  
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $student = Student::find($id);
        return view('students.show')->with('students', $student);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $student = Student::find($id);
        return view('students.edit')->with('students', $student);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $student = Student::find($id);
        $input = $request->all();
        $student->update($input);
        return redirect('student')->with('flash_message', 'student Updated!');  
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Student::destroy($id);
        return redirect('student')->with('flash_message', 'Student deleted!');  
    }
}
Create Model

Model is used to get the data from the database.

php artisan make:model Student

C:\xampp\htdocs\laravel9\blog>php artisan make:model Student

blog\app\Models\Student.php
Add code

//blog\app\Models\Student.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    use HasFactory;
    protected $table = 'students';
    protected $primaryKey = 'id';
    protected $fillable = ['name', 'address', 'mobile'];
}
Create Views
Create a Folder inside the resources-views

inside the views folder create students folder

Bootstrap 5 https://getbootstrap.com/docs/5.1/getting-started/download/

blog\resources\views\students\layout.blade.php

//blog\resources\views\students\layout.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Student Laravel 9 CRUD</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
  
<div class="container">
    @yield('content')
</div>
  
</body>
</html>
blog\resources\views\students\index.blade.php
//blog\resources\views\students\index.blade.php
@extends('students.layout')
@section('content')
    <div class="container">
        <div class="row" style="margin:20px;">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h2>Laravel 9 CRUD (Create, Read, Update and Delete)</h2>
                    </div>
                    <div class="card-body">
                        <a href="{{ url('/student/create') }}" class="btn btn-success btn-sm" title="Add New Student">
                            Add New
                        </a>
                        <br/>
                        <br/>
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Name</th>
                                        <th>Address</th>
                                        <th>Mobile</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                @foreach($students as $item)
                                    <tr>
                                        <td>{{ $loop->iteration }}</td>
                                        <td>{{ $item->name }}</td>
                                        <td>{{ $item->address }}</td>
                                        <td>{{ $item->mobile }}</td>
 
                                        <td>
                                            <a href="{{ url('/student/' . $item->id) }}" title="View Student"><button class="btn btn-info btn-sm"><i class="fa fa-eye" aria-hidden="true"></i> View</button></a>
                                            <a href="{{ url('/student/' . $item->id . '/edit') }}" title="Edit Student"><button class="btn btn-primary btn-sm"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Edit</button></a>
 
                                            <form method="POST" action="{{ url('/student' . '/' . $item->id) }}" accept-charset="UTF-8" style="display:inline">
                                                {{ method_field('DELETE') }}
                                                {{ csrf_field() }}
                                                <button type="submit" class="btn btn-danger btn-sm" title="Delete Student" onclick="return confirm("Confirm delete?")"><i class="fa fa-trash-o" aria-hidden="true"></i> Delete</button>
                                            </form>
                                        </td>
                                    </tr>
                                @endforeach
                                </tbody>
                            </table>
                        </div>
 
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection
blog\resources\views\students\create.blade.php
//blog\resources\views\students\create.blade.php
@extends('students.layout')
@section('content')
 
<div class="card" style="margin:20px;">
  <div class="card-header">Create New Students</div>
  <div class="card-body">
      
      <form action="{{ url('student') }}" method="post">
        {!! csrf_field() !!}
        <label>Name</label></br>
        <input type="text" name="name" id="name" class="form-control"></br>
        <label>Address</label></br>
        <input type="text" name="address" id="address" class="form-control"></br>
        <label>Mobile</label></br>
        <input type="text" name="mobile" id="mobile" class="form-control"></br>
        <input type="submit" value="Save" class="btn btn-success"></br>
    </form>
   
  </div>
</div>
 
@stop
blog\resources\views\students\edit.blade.php
//blog\resources\views\students\edit.blade.php
@extends('students.layout')
@section('content')
 
<div class="card" style="margin:20px;">
  <div class="card-header">Edit Student</div>
  <div class="card-body">
      
      <form action="{{ url('student/' .$students->id) }}" method="post">
        {!! csrf_field() !!}
        @method("PATCH")
        <input type="hidden" name="id" id="id" value="{{$students->id}}" id="id" />
        <label>Name</label></br>
        <input type="text" name="name" id="name" value="{{$students->name}}" class="form-control"></br>
        <label>Address</label></br>
        <input type="text" name="address" id="address" value="{{$students->address}}" class="form-control"></br>
        <label>Mobile</label></br>
        <input type="text" name="mobile" id="mobile" value="{{$students->mobile}}" class="form-control"></br>
        <input type="submit" value="Update" class="btn btn-success"></br>
    </form>
   
  </div>
</div>
 
@stop
blog\resources\views\students\show.blade.php
//blog\resources\views\students\show.blade.php
@extends('students.layout')
@section('content')
 
<div class="card" style="margin:20px;">
  <div class="card-header">Students Page</div>
  <div class="card-body">
        <div class="card-body">
        <h5 class="card-title">Name : {{ $students->name }}</h5>
        <p class="card-text">Address : {{ $students->address }}</p>
        <p class="card-text">Mobile : {{ $students->mobile }}</p>
  </div>
    </hr>
  </div>
</div>
Creating Routes
blog\routes\web.php
//blog\routes\web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController; //add the ControllerNameSpace

Route::get('/', function () {
    return view('welcome');
});

Route::resource("/student", StudentController::class);
Run C:\xampp\htdocs\laravel\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Saturday, May 7, 2022

Laravel 9 Image Upload and Display in Datatable | File Storage

Laravel 9 Image Upload and Display in Datatable | File Storage

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory. 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Create the tables
php artisan make:migration create_employees_table
C:\xampp\htdocs\laravel9\blog>php artisan make:migration create_employees_table

Open new employee migrations
yourproject/database/migrations
blog\database\migrations\_create_employees_table.php
edit code blog\database\migrations\_create_employees_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('address');
            $table->string('mobile');
            $table->string('photo', 300);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('employees');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table
Creating Controller

php artisan make:controller EmployeeController --resource
C:\xampp\htdocs\laravel9\blog>php artisan make:controller EmployeeController --resource
change it with the following codes:
blog\app\Http\Controllers\EmployeeController.php
//blog\app\Http\Controllers\EmployeeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employee;

class EmployeeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $employees = Employee::all();
        return view ('employees.index')->with('employees', $employees);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('employees.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $requestData = $request->all();
        $fileName = time().$request->file('photo')->getClientOriginalName();
        $path = $request->file('photo')->storeAs('images', $fileName, 'public');
        $requestData["photo"] = '/storage/'.$path;
        Employee::create($requestData);
        return redirect('employee')->with('flash_message', 'Employee Addedd!');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
Create Model
Model is used to get the data from the database.

php artisan make:model Employee

C:\xampp\htdocs\laravel9\blog>php artisan make:model Employee

blog\app\Models\Employee.php
Add code
//blog\app\Models\Employee.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    use HasFactory;
    protected $table = 'employees';
    protected $primaryKey = 'id';
    protected $fillable = ['name', 'address', 'mobile','photo'];
}
Create Views
Create a Folder inside the resources-views

inside the views folder create employee folder
Bootstrap 5 https://getbootstrap.com/docs/5.1/getting-started/download/
blog\resources\views\employee\layout.blade.php
//blog\resources\views\employee\layout.blade.php
<head>
    <title>Laravel 9 Image Upload and Display in Datatable | File Storage</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
  
<div class="container">
    @yield('content')
</div>
  
</body>
</html>
blog\resources\views\employee\create.blade.php
//blog\resources\views\employee\create.blade.php
@extends('employees.layout')
@section('content')
<div class="card" style="margin: 20px;">
  <div class="card-header">Create New Employee</div>
  <div class="card-body">
      
      <form action="{{ url('employee') }}" method="post" enctype="multipart/form-data">
        {!! csrf_field() !!}
        <label>Name</label></br>
        <input type="text" name="name" id="name" class="form-control"></br>
        <label>Address</label></br>
        <input type="text" name="address" id="address" class="form-control"></br>
        <label>Mobile</label></br>
        <input type="text" name="mobile" id="mobile" class="form-control"></br>
        <input class="form-control" name="photo" type="file" id="photo">

        
        <input type="submit" value="Save" class="btn btn-success"></br>
    </form>
  
  </div>
</div>
@stop
blog\resources\views\employee\index.blade.php
//blog\resources\views\employee\index.blade.php
@extends('employees.layout')
@section('content')
    <div class="container">
        <div class="row">
            <div class="col-12" style="padding:20px;">
                <div class="card">
                    <div class="card-header">Laravel 9 Image Upload and Display in Datatable | File Storage</div>
                    <div class="card-body">
                        <a href="{{ url('/employee/create') }}" class="btn btn-success btn-sm" title="Add New Contact">
                            <i class="fa fa-plus" aria-hidden="true"></i> Add New
                        </a>
                        <br/>
                        <br/>
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Name</th>
                                        <th>Address</th>
                                        <th>Telephone</th> 
                                        <th>Photo</th> 
                                </thead>
                                </thead>
                                <tbody>
                                @foreach($employees as $item)
                                    <tr>
                                        <td>{{ $loop->iteration }}</td>
                                        <td>{{ $item->name }}</td>
                                        <td>{{ $item->address }}</td>
                                        <td>{{ $item->mobile }}</td>
                                        <td>
                                            <img src="{{ asset($item->photo) }}" width= '50' height='50' class="img img-responsive" />


                                        </td>
                                    </tr>
                                @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection
Creating Routes
blog\routes\web.php
//blog\routes\web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeeController; //add the ControllerNameSpace

Route::get('/', function () {
    return view('welcome');
});

Route::resource("/employee", EmployeeController::class);
Link Storage folder to public dir

php artisan storage:link
PS C:\xampp\htdocs\laravel\blog> php artisan storage:link
The [C:\xampp\htdocs\laravel\blog\public\storage] link has been connected to [C:\xampp\htdocs\laravel\blog\storage\app/public].
The links have been created.

Run C:\xampp\htdocs\laravel9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Thursday, May 5, 2022

Swiftui custom navigationbar

Swiftui custom navigationbar

ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        NavigationView {
            List(0..<20) { rs in
                NavigationLink(destination: DetailsView().navigationBarBackButtonHidden(true)) {
                    Text("Details Custom Navigation Bar \(rs)")
                }
            }
            .navigationBarTitle("Custom Navigation Bar")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
DetailsView.swift
 
//
//  DetailsView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct DetailsView: View {
    @Environment(\.presentationMode) var presentationMode
    @State var items = [Item]()
    
    var body: some View {
        //Wrap ContentView into a NavigationView
            List(items) { item in
                Text(item.name)
            }
            //Add navigation bar title
            .navigationTitle("Todo List")
            //Initialize toolbar
            .toolbar(content: {
                //Declare one ToolBarItem for each navigation bar button and set the position
                ToolbarItem(placement: .navigationBarLeading) {
                    Button(action: {
                        self.presentationMode.wrappedValue.dismiss()    
                    }) {
                        Image(systemName: "chevron.backward")
                            .imageScale(.large)
                    }
                }
                
                ToolbarItem(placement: .navigationBarLeading) {
                    Button(action: {
                            addTask()
                    }) {
                        Image(systemName: "plus.circle")
                            .imageScale(.large)
                    }
                }
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: {
                            removeTask()
                    }) {
                        Image(systemName: "minus.circle")
                            .imageScale(.large)
                    }
                }
            })
    }
    
    func addTask() {
        let item = Item(id: items.count+1, name: "Sample Todo List")
        items.append(item)
    }
    
    func removeTask() {
        items.removeLast()
    }
}

struct DetailsView_Previews: PreviewProvider {
    static var previews: some View {
        DetailsView()
    }
}


struct Item : Identifiable {
    var id : Int
    var name : String
}

Django Mysql User Authentication - Login, register and Logout

Django Mysql User Authentication - Login, register and Logout

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Register App myapp and
Connect to MySQL Database

devproject/settings.py
//devproject/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]
   
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\devproject>python manage.py makemigrations
C:\django\devproject>python manage.py migrate
Creating View
myapp/views.py
//myapp/views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import logout
from django.shortcuts import HttpResponseRedirect
 
def signup(request):
    if request.user.is_authenticated:
        return redirect('/')
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect('/')
        else:
            return render(request, 'signup.html', {'form': form})
    else:
        form = UserCreationForm()
        return render(request, 'signup.html', {'form': form})
  
def home(request): 
    return render(request, 'home.html')
  
 
def signin(request):
    if request.user.is_authenticated:
        return render(request, 'home.html')
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('/profile') #profile
        else:
            msg = 'Error Login'
            form = AuthenticationForm(request.POST)
            return render(request, 'login.html', {'form': form, 'msg': msg})
    else:
        form = AuthenticationForm()
        return render(request, 'login.html', {'form': form})
 
def profile(request): 
    return render(request, 'profile.html')
  
def signout(request):
    logout(request)
    return redirect('/')
devproject/urls.py
//devproject/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home'),
    path('signin/',views.signin, name='signin'),
    path('signout/',views.signout, name='signout'),
    path('signup/',views.signup, name='signup'),
    path('profile/',views.profile, name='profile'),
]
myapp/templates/index.html
//myapp/templates/home.html
{% extends 'base.html' %}
 
{% block title %}Login{% endblock %}
 
{% block content %}
   <h2>Welcome!</h2>
   {% if user.is_authenticated %}
      Hi {{ user.username }}!
      <a href="/signout" class="btn btn-danger">Logout</a>
    {% else %}
      <a href="/signin" class="btn btn-primary"><span class="glyphicon glyphicon-log-in"></span>Login</a> 
      <a href="/signup" class="btn btn-success">Signup</a>
    {% endif %}
{% endblock %}
myapp/templates/base.html
//myapp/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}Django Mysql User Authentication - Login, register and Logout{% endblock %}</title>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
  <div class="container">
  <header>
    <h1>Django Mysql User Authentication - Login, register and Logout</h1>
  </header>
  <hr>
  <main>
    {% block content %}
    {% endblock %}
  </main>
  <hr>
  </div>
</body>
</html>
myapp/templates/login.html
//myapp/templates/login.html
{% extends 'base.html' %}
 
{% block title %}Login{% endblock %}
 
{% block content %}
  <h2>Login</h2> {{ msg }}
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="btn btn-primary">Login</button>
  </form>
{% endblock %}
myapp/templates/signup.html
//myapp/templates/signup.html
{% extends 'base.html' %}
 
{% block content %}
  <h2>Sign up</h2>
  <form method="post">
    {% csrf_token %}
    {% for field in form %}
      <p>
        {{ field.label_tag }}<br>
        {{ field }}
        {% for error in field.errors %}
          <p style="color: red">{{ error }}</p>
        {% endfor %}
      </p>
    {% endfor %}
    <button type="submit" class="btn btn-success">Sign up</button>
  </form>
{% endblock %}
myapp/templates/profile.html
//myapp/templates/profile.html
{% extends 'base.html' %}
 
{% block title %}Login{% endblock %}
 
{% block content %}
   <h2>Welcome!</h2>
   {% if user.is_authenticated %}
      Hi {{ user.username }}!
      <a href="/signout" class="btn btn-danger">Logout</a>
    {% else %}
      <a href="/signin" class="btn btn-primary"><span class="glyphicon glyphicon-log-in"></span>Login</a> 
      <a href="/signup" class="btn btn-success">Signup</a>
    {% endif %}
{% endblock %}
Run : C:\django\devproject>python manage.py runserver

SwiftUI Dessert App UI

SwiftUI Dessert App UI
ContentView.swift
 
//
//  ContentView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
 
    @State private var showDetails = false
    @State private var selectedItem = dessertData[0]
    
    var body: some View {
        NavigationView {
            ZStack {
                Color("Color")
                VStack {
                    HomeTopBar()
                    SearchBarView()
                    ScrollView(.vertical, showsIndicators: false) {
                        VStack {
                            ForEach(dessertData, id: \.self) { item in
                                Button(action: {
                                    showDetails = true
                                    selectedItem = item
                                }, label: {
                                    DessertItemView(item: item)
                                })
                            }
                            .background(
                            NavigationLink(
                                destination: DessertDetails(dessert: selectedItem)
                                    .navigationBarBackButtonHidden(true), isActive: $showDetails) {
                                    EmptyView()
                                }
                            )
                        }
                    }
                    Spacer()
                }
            }
            .edgesIgnoringSafeArea(.all)
        }
    }
}

struct DessertItemView: View {
    var item: Dessert
    
    var body: some View {
        ZStack(alignment: .topLeading) {
            HStack(spacing: 16) {
                Image(item.image)
                    .resizable()
                    .scaledToFill()
                    .clipShape(Circle())
                    .frame(width: 80, height: 80)
                  
                VStack(alignment: .leading) {
                    Text(item.name)
                        .font(.system(size: 16, weight: .regular))
                        .padding(.trailing, 20)
                        .foregroundColor(.gray)
                }
                Spacer()
                  
                Text(item.price)
                    .font(.system(size: 14, weight: .semibold))
                    .padding()
                    .foregroundColor(.green)
                
            }
        }
        .background(Color.white)
        .cornerRadius(40)
        .padding(.horizontal, 20)
        .padding(.vertical,5)
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
HomeTopBar.swift
 
//
//  HomeTopBar.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct HomeTopBar: View {
    
    var height = UIScreen.main.bounds.height
    
    var body: some View {
        HStack{
            Text("Home")
                .fontWeight(.bold)
                .frame(alignment: .center)
                .navigationBarItems(
                    leading:
                        Button(action: {}) {
                            Image(systemName: "slider.horizontal.3")
                                .font(.title)
                                .padding(.horizontal)
                        }
                    )
        }
        .foregroundColor(Color.black)
        .padding()
        .padding(.top, height < 750 ? 0 : 50)
    }
}

struct HomeTopBar_Previews: PreviewProvider {
    static var previews: some View {
        HomeTopBar()
    }
}
SearchBarView.swift
 
//
//  SearchBarView.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct SearchBarView: View {
    
    @State var searchKey: String = ""
    
    var body: some View {
        HStack {
            Image(systemName: "magnifyingglass")
                .foregroundColor(.black)
                .padding()
            TextField("Search ...", text: $searchKey)
        }
        .background(Color.white)
        .cornerRadius(30)
        .padding(.horizontal, 25)
        .padding(.bottom)
    }
}

struct SearchBarView_Previews: PreviewProvider {
    static var previews: some View {
        SearchBarView()
    }
}
DessertDetails.swift
 
//
//  DessertDetails.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import SwiftUI

struct DessertDetails: View {
    @Environment(\.presentationMode) var presentationMode
    @State var dessert: Dessert = dessertData[2]
    var body: some View {
        VStack(alignment: .leading) {
            Header(image: dessert.image)
            VStack(alignment: .leading) {
                ScrollView(.vertical, showsIndicators: false) {
                    VStack(alignment: .leading) {
                        Text(dessert.name)
                            .foregroundColor(.primary)
                            .font(.title)
                            .fontWeight(.bold)
                            .padding(.horizontal)
                            .padding(.vertical, 10)
                        HStack {
                            Text(dessert.price)
                                .font(.title3)
                                .fontWeight(.bold)
                            
                            Spacer()
                            AmountView()
                        }
                        .padding(.horizontal)
                        
                        HStack {
                            SubInfoView(image: "car", info: "Free Delivery")
                            Spacer()
                            SubInfoView(image: "timer", info: "20min")
                        }
                        .padding(.top, 20)
                        .padding()
                        
                        Text("Description :")
                            .fontWeight(.medium)
                            .padding(.horizontal)
                        
                        Text(dessert.description)
                            .foregroundColor(.gray)
                            .fontWeight(.light)
                            .padding()
                    }
                    
                }
            }
            
            Button(action: {
                
            }) {
                Text("Add to Cart")
                    .foregroundColor(.white)
            }
            .padding()
            .frame(width: UIScreen.main.bounds.width / 1.1)
            .background(Color.green)
            .cornerRadius(35)
            .padding()
            
            Spacer()
        }
        .edgesIgnoringSafeArea(.all)
        .statusBar(hidden: true)
        .toolbar(content: {
            ToolbarItem(placement: .navigationBarLeading) {
                Button(action: {
                    self.presentationMode.wrappedValue.dismiss()
                }) {
                    Image(systemName: "chevron.backward")
                        .imageScale(.large)
                }
             }
             ToolbarItem(placement: .navigationBarTrailing) {
                 Button(action: {
                                        
                 }) {
                     Image(systemName: "heart")
                         .imageScale(.large).foregroundColor(.red)
                 }
             }
        })
    }
}

struct SubInfoView: View {
    var image: String
    var info: String
    var body: some View {
        HStack(spacing: 8) {
            Image(systemName: image)
            Text(info)
        }
    }
}

struct AmountView: View {
    
    @State var count = 1
    
    var body: some View {
        HStack {
            Button(action: {
                if self.count != 0{
                    self.count -= 1
                }
            }) {
                Text("-")
                    .font(.title)
                    .foregroundColor(.black)
                    .frame(width: 35, height: 35)
                    .background(Circle().stroke().foregroundColor(Color.green))
            }
            
            Text("\(self.count)")
                .font(.title2)
                .fontWeight(.bold)
            
            Button(action: {
                self.count += 1
            }) {
                Text("+")
                    .font(.title)
                    .foregroundColor(.black)
                    .frame(width: 35, height: 35)
                    .background(Circle().stroke().foregroundColor(Color.green))
            }
        }
    }
}

struct Header: View {
    var image: String
    var body: some View {
        ZStack(alignment: .top) {
            Image(image)
                .resizable()
                .scaledToFill()
                .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height / 2)
                .cornerRadius(45)
        }
    }
}

struct DessertDetails_Previews: PreviewProvider {
    static var previews: some View {
        DessertDetails()
    }
}
Model.swift
 
//
//  Model.swift
//  SwiftUIProject
//
//  Created by Cairocoders
//

import Foundation

struct Dessert: Identifiable, Hashable {
    public var id: Int
    public var image: String
    public var name: String
    public var price: String
    public var description: String
}

var dessertData = [
    Dessert(id: 0, image: "desert1", name: "Leche Flan", price: "$2.99", description: "Leche Flan is a dessert made-up of eggs and milk with a soft caramel on top. It resembles crème caramel and caramel custard."),
    Dessert(id: 1, image: "desert2", name: "Maja Blanca", price: "$2.02", description: "Maja Blanca is a Filipino dessert made from coconut milk, cornstarch, and sugar. Often called Coconut Pudding, this luscious dessert is easy to make"),
    Dessert(id: 2, image: "desert3", name: "Yema", price: "$1.00", description: "Yema is a type of Filipino candy named after the Spanish term for egg yolks. I don't see the reason as to why not because egg yolk is a major ingredient "),
    Dessert(id: 3, image: "desert4", name: "Ube Halaya", price: "$3.99", description: "Ube Halaya or is a type of Filipino jam made from purple yam. It's commonly served as a midday snack or after-meal dessert"),
    Dessert(id: 4, image: "desert5", name: "Buko Salad", price: "$1.99", description: "The Buko Salad Recipe is prepared with young shredded coconut, canned fruits, cream and sweetened milk. A very popular dessert in every parties or occasion."),
    Dessert(id: 5, image: "desert6", name: "Polvoron", price: "$0.99", description: "Polvoron is a type of shortbread popular in Spain and its former colonies in Latin America and the Philippines."),
    Dessert(id: 6, image: "desert7", name: "Pastillas", price: "$0.85", description: "Pastillas de leche are sweet milk candies that are usually served for dessert. An authentic recipe will require the use of Carabao's"),
    Dessert(id: 7, image: "desert8", name: "Cassava Cake", price: "$1.99", description: "Cassava Cake is a classic Filipino dessert made from grated cassava (manioc). Cassava is also known as kamoteng kahoy and balinghoy"),
]

Monday, May 2, 2022

Laravel 9 Auth User Post using Jquery AJAX

Laravel 9 Auth User Post using Jquery AJAX

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory. 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Creating Controller

php artisan make:controller PostController
C:\xampp\htdocs\laravel9\blog>php artisan make:controller PostController
change it with the following codes:
blog\app\Http\Controllers\PostController.php
//blog\app\Http\Controllers\PostController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use Auth;
use App\Models\Post; //add Post Model

class PostController extends Controller
{
    public function getPost(){
    	$posts = DB::table('posts')
    			->join('users', 'users.id', '=', 'posts.userid')
    			->select('posts.id as postid', 'posts.*', 'users.id as userid', 'users.*')
    			->orderBy('posts.created_at', 'desc')
    			->get();
 
		return view('postlist', compact('posts'));
    }
 
    public function post(Request $request){
    	if ($request->ajax()){
    		$user = Auth::user();
	    	$post = new Post;
 
	    	$post->userid = $user->id;
	    	$post->post = $request->input('post');
 
	  		$post->save();
 
    		return response($post);
    	}
    }
}
Creating Model
php artisan make:model Post -m
C:\xampp\htdocs\laravel9\blog>php artisan make:model Post -m

This will create our model file located : blog\app\Models\Post.php

we put -m when we create our model.
this will automatically make the migration for our model and you will see that in yourproject/database/migrations
blog\database\migrations\create_posts_table.php
edit code blog\database\migrations\create_posts_table.php
//blog\database\migrations\create_posts_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('userid');
            $table->text('post');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table

Creating our User Auth
composer require laravel/ui
php artisan ui vue --auth

C:\xampp\htdocs\laravel9\blog>composer require laravel/ui
C:\xampp\htdocs\laravel9\blog>php artisan ui vue --auth

Creating Routes
blog\routes\web.php
<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/show', 'App\Http\Controllers\PostController@getPost');
Route::post('/post', 'App\Http\Controllers\PostController@post');
Route::get('/home', 'App\Http\Controllers\HomeController@index');
Creating Views
blog\resources\views\home.blade.php
//blog\resources\views\home.blade.php
@extends('layouts.app')

@section('content')
<div class="container">
    <h1 class="page-header text-center">Laravel 9 Auth User Post using Jquery AJAX</h1>
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-body">
                    <form id="postForm">
                        <textarea class="form-control" name="post" id="post" placeholder="What's on your mind?"></textarea>
                        <button type="button" id="postBtn" class="btn btn-primary" style="margin-top:5px;"><i class="fa fa-pencil-square-o"></i> POST</button>
                    </form>
                </div>
            </div>
            <div id="postList"></div>
        </div>
    </div>
</div>
@endsection
 
@section('script')
    <script type="text/javascript">
        $(document).ready(function(){

            showPost();
 
            $('#postBtn').click(function(){
                var post = $('#post').val(); 
                if(post==''){
                    alert('Please write a Post first!');
                    $('#post').focus();
                }
                else{
                    $.ajax({
                        type: 'POST',
                        url: '/post',
                        data: 'post=' + post +'&_token=' +"{{ csrf_token() }}",
                        type: "post",
                        success: function(){
                            alert("Success");
                            showPost();
                            $('#postForm')[0].reset();
                        },
                    });
                }
            });
 
        });
 
        function showPost(){
            $.ajax({
                url: '/show',
                success: function(data){
                    $('#postList').html(data); 
                },
            });
        }
    </script>
@endsection
blog\resources\views\postlist.blade.php
//blog\resources\views\postlist.blade.php
@extends('layouts.app')

@section('content')

@foreach($posts as $post)
<div class="container">
    <div class="row justify-content-center">
        <div class="col-12">

	<div class="panel panel-default">
		<div class="panel-body">
			<p style="font-size:16px;"><b>{{ $post->name }}</b> added a post.</p>
			<p style="font-size:11px; margin-top:-10px;">{{ date('M d, Y h:i A', strtotime($post->created_at)) }}</p>
			<h3 style="padding-top:30px; padding-bottom:30px;">{{ $post->post }}</h3>
		</div>
		<div class="panel-footer">
			<div class="row">
				<div class="col-md-2">
					<button class="btn btn-primary btn-sm"><i class="fa fa-thumbs-up"></i> <span>Like</span></button>
				</div>
				<div class="col-md-10" style="margin-left:-40px;">
					<button type="button" class="btn btn-primary btn-sm comment" value="{{ $post->postid }}"><i class="fa fa-comments"></i> Comment</button>
				</div>
			</div>
		</div>
	</div>
	<div class="" id="comment_{{ $post->postid }}">
	</div>
		</div>
	</div>
</div>
@endforeach

@endsection
blog\resources\views\layouts\app.blade.php
//blog\resources\views\layouts\app.blade.php
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    {{ config('app.name', 'Laravel') }}
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav me-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ms-auto">
                        <!-- Authentication Links -->
                        @guest
                            @if (Route::has('login'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                                </li>
                            @endif

                            @if (Route::has('register'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                </li>
                            @endif
                        @else
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->name }}
                                </a>

                                
                                <div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4">
            @yield('content')
        </main>
    </div>
    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>
    @yield('script')
</body>
</html>
Run C:\xampp\htdocs\laravel9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Friday, April 29, 2022

Python Django Pagination Mysql with Bootstrap 5

Python Django Pagination Mysql with Bootstrap 5

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

CREATE TABLE `employee` (
  `id` bigint(20) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(254) NOT NULL,
  `contact` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `employee` (`id`, `name`, `email`, `contact`) VALUES
(1, 'Cairocoders', 'cairocoders@gmail.com', '35345345'),
(2, 'clydey Ednalan', 'calyde@gmail.com', '6456'),
(3, 'Airi Satou', 'Airi Satou@gmail.com', '45345435'),
(4, 'Angelica Ramos', 'Angelica Ramos', '435345345'),
(5, 'Ashton Cox', 'Ashton Cox@gmail.com', '35345345'),
(6, 'Bradley Greer', 'Bradley Greer', '3453453'),
(7, 'Brenden Wagner', 'Brenden Wagner@gmail.com', '5656'),
(8, 'Brielle Williamson', 'Brielle Williamson@gmail.com', '56456'),
(9, 'Bruno Nash', 'Bruno Nash@gmail.com', '456456'),
(10, 'Caesar Vance', 'Caesar Vance@gmail.com', '45345'),
(11, 'Cara Stevens', 'Cara Stevens@gmail.com', 'ertert'),
(12, 'Cedric Kelly', 'Cedric Kelly@gmail.com', '565656'),
(13, 'Charde Marshall', 'Charde Marshall@gmail.com', '67567'),
(14, 'Colleen Hurst', 'Colleen Hurst@gmail.com', '979789'),
(15, 'Dai Rios', 'Dai Rios@gmail.com', '7868678'),
(16, 'Donna Snider', 'Donna Snider@gamil.com', '77868');
Register App myapp and
Connect to MySQL Database
devproject/settings.py
 
//devproject/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]
  
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}
Model
myapp/models.py
 
//myapp/models.py
from django.db import models
 
# Create your models here.
class Employee(models.Model):  
    name = models.CharField(max_length=100)  
    email = models.EmailField()  
    contact = models.CharField(max_length=15) 
  
    class Meta:  
        db_table = "employee"
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\devproject>python manage.py makemigrations
C:\django\devproject>python manage.py migrate
Creating View
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render, redirect  
from myapp.models import Employee  #models.py
 
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# Create your views here.   

def index(request):
    emplist = Employee.objects.all() 
    page = request.GET.get('page', 1)
 
    paginator = Paginator(emplist, 5)
    try:
        employees = paginator.page(page)
    except PageNotAnInteger:
        employees = paginator.page(1)
    except EmptyPage:
        employees = paginator.page(paginator.num_pages)
 
    return render(request, 'index.html', { 'employees': employees })
devproject/urls.py
 
//devproject/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index')
]
myapp/templates/index.html
 
//myapp/templates/index.html
<!DOCTYPE html>  
<html lang="en">  
<head>  
<meta charset="UTF-8">  
<title>Python Django Pagination Mysql with  Bootstrap 5</title> 
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head> 
<body>
<div class="container">
  <div class="row">
      <div class="col-12">
          <h2>Python Django Pagination Mysql with  Bootstrap 5</h2>  
          <h4>Employees</h4>  
        <table id="bootstrapdatatable" class="table table-striped table-bordered" width="100%">
          <thead>
            <tr>
              <th>Name</th>
              <th>Contact</th>
              <th>Email</th>
            </tr>
          </thead>
          <tbody>
            {% for rs_emp in employees %}
              <tr>
              <td>{{ rs_emp.name }}</td>
              <td>{{ rs_emp.contact }}</td>
              <td>{{ rs_emp.email }}</td>
              </tr>
            {% endfor %}
          </tbody>
        </table>
      
      <nav aria-label="...">
      {% if employees.has_other_pages %}
        <ul class="pagination">
          {% if employees.has_previous %}
            <li class="page-item"><a class="page-link" href="?page={{ employees.previous_page_number }}">Previous</a></li>
          {% else %}
            <li class="page-item disabled"><span class="page-link">Previous</span></li>
          {% endif %}

          {% for i in employees.paginator.page_range %}
            {% if employees.number == i %}
            <li class="page-item active" aria-current="page"><a class="page-link" href="#">{{ i }}</a></li>
            {% else %}
            <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
            {% endif %}
          {% endfor %}

          {% if employees.has_next %}
            <li class="page-item"><a class="page-link" href="?page={{ employees.next_page_number }}">Next</a></li>
          {% else %}
            <li class="page-item disabled"><span class="page-link">Next</span></li>
          {% endif %}
        </ul>
      {% endif %}
      </nav>

    </div>        
  </div> 
</div> 
</body> 
</html>
Run : C:\django\devproject>python manage.py runserver

How to get PHP Session Value in jQuery

How to get PHP Session Value in jQuery

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

getssionjquery.php
//getssionjquery.php
<!DOCTYPE html>
<html>
<head>
	<title>How to get PHP Session Value in jQuery</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
	<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
<?php session_start(); ?>
<div class="container">
	<h1 class="page-header text-center">How to get PHP Session Value in jQuery</h1>
	<div class="row">
		<div class="col-6">
			<h3>Set Session Value</h3>
			<form method="POST" action="session.php">
				<input type="text" name="session_value" class="form-control" placeholder="Input Value" required>
				<div style="margin-top:10px;">
				<button type="submit" class="btn btn-primary">Set Value</button> <a href="unset.php" type="button" class="btn btn-danger">Unset Value</a>
				</div>
			</form>
 
			<button type="button" id="checkSession" class="btn btn-info" style="margin-top:30px;">Check Session in jQuery</button>
		</div>
	</div>
 
	<input type="hidden" value="<?php
		if(isset($_SESSION['value'])){
			echo $_SESSION['value'];
		} 
	?>" id="session">
</div>
<script>
$(document).ready(function(){
	//check session
	$('#checkSession').click(function(){
		var session = $('#session').val();
		if(session == ''){
			alert('Session not Set');
			console.log('Session not Set');
		}
		else{
			alert('Current Session Value: '+session);
			console.log(session);
		}
	});
});
</script>
</body>
</html>
session.php
//session.php
<?php
	session_start();
 
	$session_value=$_POST['session_value'];
	$_SESSION['value']=$session_value;
 
	header('location:getsessionjquery.php');
?>
unset.php
//unset.php
<?php
	session_start();
	unset($_SESSION['value']);
	header('location:getsessionjquery.php');
?>

Thursday, April 28, 2022

Django File Upload Save to Mysql Database

Django File Upload Save to Mysql Database

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Mysql tabase table
CREATE TABLE `student` (
  `id` bigint(20) NOT NULL,
  `firstname` varchar(50) NOT NULL,
  `lastname` varchar(50) NOT NULL,
  `email` varchar(254) NOT NULL,
  `file` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Register App myapp and
Connect to MySQL Database
//devproject/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]
 
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}
Model
myapp/models.py
//myapp/models.py
from django.db import models

# Create your models here.
class StudentForm(models.Model):  
    firstname = models.CharField("Enter first name", max_length=50)  
    lastname  = models.CharField("Enter last name", max_length = 50)  
    email     = models.EmailField("Enter Email")  
    file      = models.FileField() # for creating file input  
  
    class Meta:  
        db_table = "student"
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\my_project_django\testdev>python manage.py makemigrations
C:\my_project_django\testdev>python manage.py migrate
Creating View
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render
from django.http import HttpResponse  
from myapp.functions import handle_uploaded_file  #functions.py
from myapp.forms import StudentForm #forms.py
  
def index(request):  
    if request.method == 'POST':  
        student = StudentForm(request.POST, request.FILES)  
        if student.is_valid():  
            handle_uploaded_file(request.FILES['file'])  
            model_instance = student.save(commit=False)
            model_instance.save()
            return HttpResponse("File uploaded successfuly")  
    else:  
        student = StudentForm()  
        return render(request,"index.html",{'form':student}) 
myapp/forms.py
 
////myapp/forms.py
from django import forms  
from myapp.models import StudentForm  #models.py
    
class StudentForm(forms.ModelForm):  
    class Meta:  
        model = StudentForm  
        fields = "__all__"

    def __init__(self, *args, **kwargs):
            super(StudentForm, self).__init__(*args, **kwargs)
            for field_name, field in self.fields.items():
                field.widget.attrs['class'] = 'form-control'	
myapp/functions.py
 
//myapp/functions.py
def handle_uploaded_file(f):  
    with open('myapp/static/upload/'+f.name, 'wb+') as destination:  
        for chunk in f.chunks():  
            destination.write(chunk) 
myapp/urls.py
 
//myapp/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index')
]			
myapp/templates/index.html
//myapp/templates/index.html
<html>
<head>
<title>Django File Upload - cairocoders</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container" style="padding:20px;">
    <div class="row">
        <div class="col-12">
            <p><h1>Django File Upload Save to Mysql Database</h1></p>
            <form method="POST" class="post-form" enctype="multipart/form-data">  
                    {% csrf_token %}  
                    {{ form.as_p }}  
                <button type="submit" class="btn btn-primary">Save</button>  
            </form>  
        </div>
    </div>
</div>
</body>  
</html>
Run : C:\django\devproject>python manage.py runserver

Tuesday, April 26, 2022

Python Django How to setup MySQL Databse with DataTables

Python Django How to setup MySQL Databse with DataTables

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

Datatables
https://datatables.net/
DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table.

Register App myapp and
Connect to MySQL Database

devtest/settings.py
 
//devproject/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #add myapp
]

DATABASES = {
    'default': {
		'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
		'USER': 'root',
		'PASSWORD': '',
		'HOST': 'localhost',
		'PORT': '3306'
    }
}
Model Class
 
//myapp/models.py
from django.db import models

# Create your models here.
class User(models.Model):
	id = models.IntegerField()
	name = models.CharField(max_length=50)
	email = models.CharField(max_length=100)
	phone = models.IntegerField(max_length=10)
	address = models.CharField(max_length=250)
	
	class Meta:  
		db_table = "user"
		app_label = ''
	
	def __str__(self):
		return self
database user table
 
//database user table
CREATE TABLE `user` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `email` varchar(100) NOT NULL,
  `phone` int unsigned NOT NULL,
  `address` varchar(250) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

insert  into `user`(`id`,`name`,`email`,`phone`,`address`) values 
(1,'cairocoders','cairocoders@gmail.com',2147483647,'Olongapo City'),
(2,'tutorial101','turorial101@gmail.com',34256780,'Olongapo City');
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\my_project_django\testdev>python manage.py makemigrations
C:\my_project_django\testdev>python manage.py migrate
Creating View
myapp/views.py
 
//myapp/views.py
from django.http import HttpResponse
from django.template import loader
from django.shortcuts import render

from .models import User


def index(request):
	user_list = User.objects.order_by('id')
	
	#template = loader.get_template('index.html')
	
	#context = {
    #    'user_list': user_list,
    #}
    
	#return HttpResponse(template.render(context, request))
	
	context = {'user_list': user_list}
	return render(request, 'index.html', context)
myapp/urls.py
 
//myapp/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views #add myapp

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index')
]
myapp/templates/index.html
//myapp/templates/index.html
{% extends "base.html" %}

{% block content %}
{% if user_list %}
	<table id="table" class="table table-bordered table-striped">
		<thead>
			<th>Id</th>
			<th>Name</th>
			<th>Email</th>
			<th>Phone</th>
			<th>Address</th>
		</thead>
		<tbody>
		{% for user in user_list %}
			<tr>
				<td>{{user.id}}</td>
				<td>{{user.name}}</td>
				<td>{{user.email}}</td>
				<td>{{user.phone}}</td>
				<td>{{user.address}}</td>
			</tr>
		{% endfor %}
		</tbody>
    </table>
{% else %}
    <p>No user record available</p>
{% endif %}
{% endblock %}
myapp/templates/base.html
 
//myapp/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
<title>Python Django How to setup MySQL Databse</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
<link rel = "stylesheet" type = "text/css" href = "https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css"/>
</head>
<body>
<div class="container" style="padding:20px;">
    <div class="col-12">
        <h3 class="text-primary">Python Django How to setup MySQL Databse with DataTables</h3> 
        <hr style="border-top:1px dotted #ccc;"/>
        {% block content %} {% endblock %}
    </div>
</div>	
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src = "https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
    $('#table').DataTable();
});
</script>
</body>
</html>
Run : C:\django\devproject>python manage.py runserver

Related Post