article

Saturday, May 9, 2020

Python Django Simple Forms Using Widget Tweaks


Python Django Simple Forms Using Widget Tweaks

Tweak the form field rendering in templates, not in python-level form definitions. Altering CSS classes and HTML attributes is supported.


That should be enough for designers to customize field presentation (using CSS and unobtrusive javascript) without touching python code.

url https://pypi.org/project/django-widget-tweaks/

Install widget-tweaks

$ pip install django-widget-tweaks

Now add widget_tweaks to your INSTALLED_APPS:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
    'widget_tweaks',
]

To start using, must load the template tag in the template you want to use its functions:

{% load widget_tweaks %}

#views.py
from django.shortcuts import render, redirect
from myapp.models import Member
from myapp.forms import MemberForm

# Create your views here.
def index(request):
    members = Member.objects.all()
    return render(request, 'index.html', { 'members': members })

def add_member(request):
    if request.method == 'POST':
        form = MemberForm(request.POST)
        if form.is_valid():
            Member = form.save()
            return redirect('/')
    else:
        form = MemberForm()
    return render(request, 'add_member.html', { 'form': form })
#models.py
from django.db import models
 
# Create your models here.
class Member(models.Model):
    username = models.CharField(max_length=40)
    firstname = models.CharField(max_length=40)
    lastname = models.CharField(max_length=40)
    email = models.EmailField(max_length=254)
    bio = models.TextField(max_length=500)
    created = models.DateTimeField(auto_now_add=True)
  
    def __str__(self):
        return self.firstname + " " + self.lastname
 
    class Meta:
        ordering = ['created']
   
    class Meta:  
        db_table = "blog_member"
#forms.py
from django import forms
from myapp.models import Member
 
class MemberForm(forms.ModelForm):
    class Meta:
        model = Member
        fields = ('username', 'firstname', 'lastname', 'email', 'bio',)
#settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
    'widget_tweaks', 
]
#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),
    path('add_member/',views.add_member),
]
//templates/index.html
{% extends 'base.html' %}

{% block content %}

  <h2>
    Member
    <a href="/add_member" class="btn btn-primary pull-right">
      <span class="glyphicon glyphicon-plus"></span> Add Member
    </a>
  </h2>

  <table class="table">
    <thead>
      <tr>
        <th>ID</th>
        <th>First name</th>
        <th>Last name</th>
        <th>Email</th>
        <th>Phone</th>
        <th>Bio</th>
      </tr>
    </thead>
    <tbody>
      {% for rs in members %}
        <tr>
          <td>{{ rs.id }}</td>
          <td>{{ rs.username }}</td>
          <td>{{ rs.firstname }}</td>
          <td>{{ rs.lastname }}</td>
          <td>{{ rs.email }}</td>
          <td>{{ rs.bio }}</td>
        </tr>
      {% empty %}
        <tr>
          <td colspan="6" class="text-center">No result</td>
        </tr>
      {% endfor %}
    </tbody>
  </table>

{% endblock %}
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.css' %}"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
 <title>{% block title %}Simple Forms{% endblock %}</title>
</head>
<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <a class="navbar-brand">Cairocoders</a>
        </div>
    </nav>
 <div class="container">
    <div class="col-md-12 well">
        <h3 class="text-primary">Python Django Simple Forms Using Widget Tweaks</h3>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block content %}
 
        {% endblock %}
    </div>
    </div>
</body>
</html>
//templates/add_member.html
{% extends 'base.html' %}

{% load widget_tweaks %}

{% block content %}
  <h2>Add Member</h2>
  <form method="post">
    {% csrf_token %}

    {% for hidden in form.hidden_fields %}
      {{ hidden }}
    {% endfor %}

    {% for field in form.visible_fields %}
      <div class="form-group">
        <label for="{{ field.id_for_label }}">{{ field.label }}</label>
        {% render_field field class="form-control" %}
        {% for error in field.errors %}
          <span class="help-block">{{ error }}</span>
        {% endfor %}
      </div>
    {% endfor %}

    <div class="form-group">
      <button type="submit" class="btn btn-success">
        <span class="glyphicon glyphicon-ok"></span> Save
      </button>
      <a href="/" class="btn btn-default">Cancel</a>
    </div>
  </form>
{% endblock %}

Saturday, May 2, 2020

Django User Accounts Login, register and Logout User Authentication


Django User Accounts Login, register and Logout User Authentication
#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('/')
#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),
    path('signin/',views.signin),
    path('signout/',views.signout),
    path('signup/',views.signup),
    path('profile/',views.profile),
] 
//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 %}
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}Django User Accounts{% endblock %}</title>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.css' %}"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
  <div class="container">
  <header>
    <h1>Django User Accounts</h1>
  </header>
  <hr>
  <main>
    {% block content %}
    {% endblock %}
  </main>
  <hr>
  </div>
</body>
</html>
//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 %}
//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 %}
//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 %}

Friday, May 1, 2020

Python Django CRUD With Jquery Ajax


Python Django CRUD With Jquery Ajax
 
#views.py
from django.shortcuts import render, redirect
from myapp.models import Member

# Create your views here.
def index(request):
    return render(request, 'index.html')


def create(request):
    member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'])
    member.save()
    return redirect('/')

def read(request):
    members = Member.objects.all()
    context = {'members': members}
    return render(request, 'result.html', context)

def edit(request, id):
    members = Member.objects.get(id=id)
    context = {'member': members}
    return render(request, 'edit.html', context)


def update(request, id):
    member = Member.objects.get(id=id)
    member.firstname = request.POST['firstname']
    member.lastname = request.POST['lastname']
    member.save()
    return redirect('/')


def delete(request, id):
    member = Member.objects.get(id=id)
    member.delete()
    return redirect('/')
 
#models.py
from django.db import models

# Create your models here.
class Member(models.Model):
    firstname = models.CharField(max_length=40)
    lastname = models.CharField(max_length=40)
 
    created = models.DateTimeField(auto_now_add=True)
 
    def __str__(self):
        return self.firstname + " " + self.lastname

    class Meta:
        ordering = ['created']
  
    class Meta:  
        db_table = "blog_member"
 
#urls.py
from django.contrib import admin  
from django.urls import path  
from myapp import views  
from django.conf.urls import url

urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('',views.index),
    url(r'^create$', views.create, name='create'),
    url(r'^read$', views.read, name='read'),
    url(r'^edit/(?P\d+)$', views.edit, name='edit'),
    url(r'^edit/update/(?P\d+)$', views.update, name='update'),
    url(r'^delete/(?P\d+)$', views.delete, name='delete'),
] 
//templates/index.html
{% extends 'base.html' %}
{% block body %}
<form class="form-inline">
    {% csrf_token %}
    <div class="form-group">
        <label>Firstname</label>
        <input type="text" id="firstname" class="form-control" style="width:30%;" required="required"/>
        <label>Lastname</label>
        <input type="text" id="lastname" class="form-control" style="width:30%;" required="required"/>
        <button type="button" id="create" class="btn btn-sm btn-primary">Create</button>
    </div>
</form>
<br />
<div id="result"></div>
{% endblock %}
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.css' %}"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <a class="navbar-brand">Cairocoders</a>
        </div>
    </nav>
    <div class="col-md-3"></div>
    <div class="col-md-6 well">
        <h3 class="text-primary">Python Django CRUD With Jquery Ajax</h3>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block body %}

        {% endblock %}
    </div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="{% static 'js/script.js' %}"></script>
</body>
</html>
//templates/edit.html
{% extends 'base.html' %}
{% block body %}
    <form>
        {% csrf_token %}
        <input type="hidden" id="member_id" value="{{ member.id }}"/>
        <div class="form-group">
            <label>Firstname</label>
            <input type="text" id="firstname" value="{{ member.firstname }}" required="required"/>
        </div>
        <div class="form-group">
            <label>Lastname</label>
            <input type="text" id="lastname" value="{{ member.lastname }}" required="required"/>
        </div>
        <div class="form-group">
            <button type="button" id="update" class="btn btn-sm btn-warning">Update</button>
        </div>
    </form>
{% endblock %}
//templates/result.html
<table class="table table-bordered">
    <thead class="alert-success">
        <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        {% for member in members %}
        <tr>
            <td>{{ member.firstname }}</td>
            <td>{{ member.lastname }}</td>
            <td><center><a class="btn btn-sm btn-warning edit" name="{{ member.id }}">Edit</a> <a class="btn btn-sm btn-danger delete" name="{{ member.id }}">Delete</a></center></td>
        </tr>
        {% endfor %}
    </tbody>
</table>
//static/js/script.js
$(document).ready(function(){
    if($('#result') != null){
        Read();
    }
    $('#create').on('click', function(){
        $firstname = $('#firstname').val();
        $lastname = $('#lastname').val();

        if($firstname == "" || $lastname == ""){
            alert("Please complete the required field");
        }else{
            $.ajax({
                url: 'create',
                type: 'POST',
                data: {
                    firstname: $firstname,
                    lastname: $lastname,
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
                },
                success: function(){
                    Read();
                    $('#firstname').val('');
                    $('#lastname').val('');
                }
            });
        }
    });

    $(document).on('click', '.edit', function(){
        $id = $(this).attr('name');
        window.location = "edit/" + $id;
    });

    $('#update').on('click', function(){
        $firstname = $('#firstname').val();
        $lastname = $('#lastname').val();

        if($firstname == "" || $lastname == ""){
            alert("Please complete the required field");
        }else{
            $id = $('#member_id').val();
            $.ajax({
                url: 'update/' + $id,
                type: 'POST',
                data: {
                    firstname: $firstname,
                    lastname: $lastname,
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
                },
                success: function(){
                    window.location = '/';
                    alert('Updated!');
                }
            });
        }

    });

    $(document).on('click', '.delete', function(){
        $id = $(this).attr('name');
        $.ajax({
            url: 'delete/' + $id,
            type: 'POST',
            data: {
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
            },
            success: function(){
                Read();
                alert("Deleted!");
            }
        });
    });

});

function Read(){
    $.ajax({
  url: 'read',
  type: 'POST',
  async: false,
  data:{
   res: 1,
   csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
  },
  success: function(response){
   $('#result').html(response);
  }
    });
}

Python Django Simple CRUD (Create Read Update Delete)


Python Django Simple CRUD (Create Read Update Delete)

#views.py
from django.shortcuts import render, redirect
from myapp.models import Member

# Create your views here.

def index(request):
    members = Member.objects.all()
    context = {'members': members}
    return render(request, 'index.html', context)

def create(request):
    member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'])
    member.save()
    return redirect('/')

def edit(request, id):
    members = Member.objects.get(id=id)
    context = {'members': members}
    return render(request, 'edit.html', context)

def update(request, id):
    member = Member.objects.get(id=id)
    member.firstname = request.POST['firstname']
    member.lastname = request.POST['lastname']
    member.save()
    return redirect('/')

def delete(request, id):
    member = Member.objects.get(id=id)
    member.delete()
    return redirect('/')
#models.py
from django.db import models

# Create your models here.
class Member(models.Model):
    firstname = models.CharField(max_length=40)
    lastname = models.CharField(max_length=40)
	
    created = models.DateTimeField(auto_now_add=True)
	
    def __str__(self):
        return self.firstname + " " + self.lastname

    class Meta:
        ordering = ['created']
		
    class Meta:  
        db_table = "blog_member"
#urls.py
from django.contrib import admin  
from django.urls import path  
from myapp import views  
from django.conf.urls import url

urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('',views.index),
    url(r'^create$', views.create, name='create'),
    url(r'^edit/(?P\d+)$', views.edit, name='edit'),
    url(r'^edit/update/(?P\d+)$', views.update, name='update'),
    url(r'^delete/(?P\d+)$', views.delete, name='delete'),
] 
//templates/index.html
{% extends 'base.html' %}
{% block body %}
<form class="form-inline"  action="create" method="POST">
    {% csrf_token %}
    <div class="form-group">
        <label for="firstname">Firstname</label>
        <input type="text" name="firstname" class="form-control" style="width:30%;" required="required"/>
        <label for="lastname">Lastname</label>
        <input type="text" name="lastname" class="form-control" style="width:30%;" required="required"/>
        <button type="submit" class="btn btn-sm btn-primary"><span class="glyphicon glyphicon-plus"></span> ADD</button>
    </div>
</form>
<br />
<table class="table table-bordered">
    <thead class="alert-warning">
        <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        {% for member in members %}
        <tr>
            <td>{{ member.firstname }}</td>
            <td>{{ member.lastname }}</td>
            <td><center><a class="btn btn-sm btn-warning" href="edit/{{ member.id }}"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a class="btn btn-sm btn-danger" href="delete/{{ member.id }}"><span class="glyphicon glyphicon-trash"></span> Delete</a></center></td>
        </tr>
        {% endfor %}
    </tbody>
</table>
{% endblock %}
//templates/edit.html
{% extends 'base.html' %}
{% block body %}
    <form method="POST" action="update/{{ members.id }}">
        {% csrf_token %}
        <div class="form-group">
            <label for="firstname">Firstname</label>
            <input type="text" name="firstname" value="{{ members.firstname }}" class="form-control" required="required"/>
        </div>
        <div class="form-group">
            <label for="lastname">Lastname</label>
            <input type="text" name="lastname" value="{{ members.lastname }}" class="form-control" required="required"/>
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-sm btn-warning"><span class="glyphicon glyphicon-edit"></span> Update</button>
        </div>
    </form>
{% endblock %}
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.css' %}"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <a class="navbar-brand">Cairocoders</a>
        </div>
    </nav>
    <div class="col-md-3"></div>
    <div class="col-md-6 well">
        <h3 class="text-primary">Python Django Simple CRUD (Create Read Update Delete)</h3>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block body %}

        {% endblock %}
    </div>
</body>
</html>

Python Django Inserting Data Using Jquery Ajax


Python Django Inserting Data Using Jquery Ajax


 
#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('/')
 
#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" 
 
#urls.py
from django.contrib import admin  
from django.urls import path  
from myapp import views  
from django.conf.urls import url

urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('',views.index),
    url(r'^insert$', views.insert, name='insert'),
] 
//templates/index.html
{% extends 'base.html' %}
{% block 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>
  <br />
  <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>
        <br />
        <div class="form-group">
            <label>Address</label>
            <input type="text" id="address" name="address" class="form-control"/>
        </div>
        <div class="col-md-4"></div>
        <div class="col-md-4 form-group">
    <button type="button" class="btn btn-primary form-control" id="submit">Submit</button>
        </div>
    </form>
    <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 %}
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.css' %}"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
 <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
 <script src="{% static 'js/script.js' %}"></script>
</head>
<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <a class="navbar-brand">Cairocoders</a>
        </div>
    </nav>
    <div class="col-md-3"></div>
    <div class="col-md-6 well">
        <h3 class="text-primary">Python Django Inserting Data Using Jquery Ajax</h3>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block body %}

        {% endblock %}
    </div>
</body>
</html>
//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 = "/";
                }
            });
        }
    });
});

Thursday, April 30, 2020

Django Jquery Ajax Check Username before Inserting Data


Django Jquery Ajax Check Username before Inserting Data

#views.py
from django.shortcuts import render, redirect
from myapp.models import Member
from django.http import JsonResponse

# 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('/')


def validate_username(request):
    username = request.GET.get('username', None)
    data = {
        'is_taken': Member.objects.filter(username=username).exists()
    }
    if data['is_taken']:
        data['error_message'] = 'A user with this username already exists.'
    return JsonResponse(data)
#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" 
#urls.py
from django.contrib import admin  
from django.urls import path  
from myapp import views  
from django.conf.urls import url

urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('',views.index),
    path('insert/',views.insert),
    url(r'^validate_username/$', views.validate_username, name='validate_username'),
] 
//templates/index.html
{% extends 'base.html' %}
{% block body %}
    <form class="" action="/insert/" method="post">
        {% csrf_token %}
        <div class="form-inline">
            <label>UserName</label>
            <input type="text" id="username" name="username" class="form-control"/>
        </div>
  <br />
  <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>
        <br />
        <div class="form-group">
            <label>Address</label>
            <input type="text" id="address" name="address" class="form-control"/>
        </div>
        <div class="col-md-4"></div>
        <div class="col-md-4 form-group">
    <input type="submit" class="btn btn-primary form-control" name="" value="Submit">
        </div>
    </form>
    <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 %}
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.css' %}"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
 <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
 <script src="{% static 'js/script.js' %}"></script>
</head>
<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <a class="navbar-brand">Cairocoders</a>
        </div>
    </nav>
    <div class="col-md-3"></div>
    <div class="col-md-6 well">
        <h3 class="text-primary">Django Jquery Ajax Check Username before Inserting Data</h3>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block body %}

        {% endblock %}
    </div>
</body>
</html>
//static/js/script.js
$(document).ready(function(){
    $("#username").change(function () {
      var username = $(this).val();

      $.ajax({
        url: '/validate_username/',
        data: {
          'username': username
        },
        dataType: 'json',
        success: function (data) {
          if (data.is_taken) {
            alert("A user with this username already exists.");
          }
        }
      });

    });
});

Django Simple Todo List


Django Simple Todo List



 
#views.py
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from myapp.models import TodoItem

# Create your views here.
def todoView(request):
    all_todo_items = TodoItem.objects.all()
    return render(request,'todolist.html', {'all_items':all_todo_items})
 
# Save
def addTodo(request):
    new_item = TodoItem(content = request.POST['content'])
    new_item.save()
    return HttpResponseRedirect('/')
 
def deleteTodo(request,todo_id):
    item_to_delete = TodoItem.objects.get(id=todo_id)
    item_to_delete.delete()
    return HttpResponseRedirect('/')
 
#models.py
from django.db import models

# Create your models here.
class TodoItem(models.Model):
    content = models.TextField()
 
    class Meta:  
        db_table = "todoitem"
 
#urls.py
from django.contrib import admin  
from django.urls import path  
from myapp import views  

urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('',views.todoView),
    path('addTodo/',views.addTodo),
    path('deleteTodo//',views.deleteTodo),
]  
//templates/todolist.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
   <title>This is My Todolist</title>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  </head>
  <body>
<div class="container-fluid text-center">    
   <div class="row content"><h1 align="center">Django Simple Todo List</h1>
      <div class="col-sm-2"></div>
      <div class="col-sm-8 text-left">
       <br />
     <div class="panel panel-default">
      <div class="panel-heading">
       <div class="row">
        <div class="col-md-9">
         <h3 class="panel-title">My To-Do List</h3>
        </div>
        <div class="col-md-3">
         <h3 class="panel-title" align="right"><a href="#">Logout</a></h3>
        </div>
       </div>
      </div>
      <div class="panel-body">
       <form method="post" id="to_do_form" action="/addTodo/" method="post">{% csrf_token %}
        <div class="input-group">
         <input type="text" name="content" id="content" class="form-control input-lg" autocomplete="off" placeholder="Title..." />
         <div class="input-group-btn">
          <button type="submit" name="submit" id="submit" class="btn btn-success btn-lg"><span class="glyphicon glyphicon-plus"></span></button>
         </div>
        </div>
       </form>
       <br />
       <div class="list-group">
        <ul class="list-wrapper">
          {% for todo_item in all_items %}
          <li class="list-group-item">{{ todo_item.content}}
         <form class="" action="/deleteTodo/{{ todo_item.id}}/" style ="display: inline;" method="post">{% csrf_token %}
           <input type="submit" name="" value="Delete" style="float:right;">
         </form>
          </li>
          {% endfor %}
        </ul>
        <br />
       </div>
      </div>
      
      </div>
      <div class="col-sm-2"></div>
     </div>
</div>
</div>
<style>
.list-wrapper {
    padding: 0;
    text-align: left;
    list-style: none;
    margin-bottom: 0;
}
</style>
 </body>
</html>

Friday, April 24, 2020

Python Django - Simple Registration & Login Form


Python Django - Simple Registration & Login Form


 
#view.py
from django.shortcuts import render, redirect, HttpResponseRedirect
from myapp.models import Member #models.py

# Create your views here.
def index(request):
    if request.method == 'POST':
        member = Member(username=request.POST['username'], password=request.POST['password'],  firstname=request.POST['firstname'], lastname=request.POST['lastname'])
        member.save()
        return redirect('/')
    else:
        return render(request, 'index.html')

def login(request):
    return render(request, 'login.html')

def home(request):
    if request.method == 'POST':
        if Member.objects.filter(username=request.POST['username'], password=request.POST['password']).exists():
            member = Member.objects.get(username=request.POST['username'], password=request.POST['password'])
            return render(request, 'home.html', {'member': member})
        else:
            context = {'msg': 'Invalid username or password'}
            return render(request, 'login.html', context)
 
#models.py
from django.db import models

# Create your models here.  
class Member(models.Model):
    firstname=models.CharField(max_length=30)
    lastname=models.CharField(max_length=30)
    username=models.CharField(max_length=30)
    password=models.CharField(max_length=12)

    def __str__(self):
        return self.firstname + " " + self.lastname
  
 
    class Meta:  
        db_table = "web_member"
 
#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),
    path('login/',views.login),
    path('home/',views.home),
]  
//templates/index.html
{% extends 'base.html' %}
{% block body %}
<form method="POST">
    {% csrf_token %}
    <div class="col-md-2">
        <a href="/login">Login</a>
    </div>
    <div class="col-md-8">
        <div class="form-group">
            <label for="username">Username</label>
            <input type="text" name="username" class="form-control" required="required">
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <input type="password" name="password" class="form-control" required="required"/>
        </div>
        <div class="form-group">
            <label for="firstname">Firstname</label>
            <input type="text" name="firstname" class="form-control" required="required"/>
        </div>
        <div class="form-group">
            <label for="lastname">Lastname</label>
            <input type="text" name="lastname" class="form-control" required="required"/>
        </div>
        <br />
        <div class="form-group">
            <button type="submit" class="btn btn-primary form-control"><span class="glyphicon glyphicon-save"></span> Submit</button>
        </div>
    </div>
</form>
{% endblock %}
//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 - Simple Registration & Login Form</title>
        {% load static %}
        <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.css' %}" />
    </head>
<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <a class="navbar-brand" href="https://tutorial101.blogspot.com">Cairocoders</a>
        </div>
    </nav>
    <div class="col-md-3"></div>
    <div class="col-md-6 well">
        <h3 class="text-primary">Python Django - Simple Registration & Login Form</h3>
        <hr style="border-top:1px dotted #000;"/>
        {% block body %}
        {% endblock %}
    </div>
</body>
</html>
//templates/login.html
{% extends 'base.html' %}
{% block body %}
<form method="POST" class="post-form" action="/home/">  
    {% csrf_token %}
    <div class="col-md-2">
         <a href="/">Signup</a>
    </div>
    <div class="col-md-8">
        <div class="form-group">
            <label for="username">Username</label>
            <input type="text" name="username" class="form-control" required="required"/>
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <input type="password" name="password" class="form-control" required="required"/>
        </div>
        <center><label class="text-danger">{{ msg }}</label></center>
        <br />
        <div class="form-group">
            <button class="btn btn-primary form-control"><span class="glyphicon glyphicon-log-in"></span> Login</button>
        </div>
    </div>
</form>

{% endblock %}

Friday, April 17, 2020

Django How to Export Data to XLS File


Django How to Export Data to XLS File

install the xlwt module

pip install xlwt


#views.py
from django.shortcuts import render  
from django.http import HttpResponse 
from django.contrib.auth.models import User
import xlwt
from myapp.models import StudentForm #models.py

def index(request):   
    return render(request,"index.html")  
 
def export_users_xls(request):
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="users.xls"'

    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('Users')

    # Sheet header, first row
    row_num = 0

    font_style = xlwt.XFStyle()
    font_style.font.bold = True

    columns = ['Username', 'First name', 'Last name', 'Email address', ]

    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style)

    # Sheet body, remaining rows
    font_style = xlwt.XFStyle()

    rows = User.objects.all().values_list('username', 'first_name', 'last_name', 'email')
    for row in rows:
        row_num += 1
        for col_num in range(len(row)):
            ws.write(row_num, col_num, row[col_num], font_style)

    wb.save(response)
    return response

def export_student_xls(request):
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="student.xls"'

    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('Student')

    # Sheet header, first row
    row_num = 0

    font_style = xlwt.XFStyle()
    font_style.font.bold = True

    columns = ['First name', 'Last name', 'Email address', ]

    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style)

    # Sheet body, remaining rows
    font_style = xlwt.XFStyle()

    rows = StudentForm.objects.all().values_list('firstname', 'lastname', 'email')
    for row in rows:
        row_num += 1
        for col_num in range(len(row)):
            ws.write(row_num, col_num, row[col_num], font_style)

    wb.save(response)
    return response
#urls.py
from django.contrib import admin  
from django.urls import path  
from myapp import views  

urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('index/', views.index), 
    path('export_users_xls/', views.export_users_xls), 
    path('export_student_xls/', views.export_student_xls), 
]  
#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")  
    bio       = models.TextField(blank=True)  
    file      = models.FileField() # for creating file input  
  
    class Meta:  
        db_table = "student"
#templates/index.html
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Django How to Export Data to XLS File</title>
  </head>
  <body>
  <p><h2>Django How to Export Data to XLS File</h2></p>
 <p><h4><a href="/export_users_xls">Export all users</a></h4></p>
 <p><h4><a href="/export_student_xls">Export all Students</a></h4></p>
  </body>
</html>

Thursday, April 16, 2020

Django How to Export Data to CSV File


Django How to Export Data to CSV File

Export Data to CSV File No need to install dependencies. Use it if you do not need any fancy formating.

import csv

#views.py
from django.shortcuts import render  
from django.http import HttpResponse 
from django.contrib.auth.models import User
import csv
from myapp.models import StudentForm #models.py

def index(request):   
    return render(request,"index.html")  
 
def export_users_csv(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="users.csv"'
 
    writer = csv.writer(response)
    writer.writerow(['Username', 'First name', 'Last name', 'Email address'])
 
    users = User.objects.all().values_list('username', 'first_name', 'last_name', 'email')
    for user in users:
        writer.writerow(user)

    return response

def export_student_csv(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="student.csv"'
 
    writer = csv.writer(response)
    writer.writerow(['First name', 'Last name', 'Email address'])
 
    student = StudentForm.objects.all().values_list('firstname', 'lastname', 'email')
    for student_rs in student:
        writer.writerow(student_rs)

    return response
 
#urls.py
from django.contrib import admin  
from django.urls import path  
from myapp import views  

urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('index/', views.index), 
    path('export_users_csv/', views.export_users_csv), 
    path('export_student_csv/', views.export_student_csv), 
]  
#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")  
    bio       = models.TextField(blank=True)  
    file      = models.FileField() # for creating file input  
  
    class Meta:  
        db_table = "student"
//templates/index.html
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Django How to Export Data to CSV File</title>
  </head>
  <body>
  <p><h2>Django How to Export Data to CSV File</h2></p>
 <p><h4><a href="/export_users_csv">Export all users</a></h4></p>
<p><h4><a href="/export_student_csv">Export all Students</a></h4></p>
  </body>
</html>

Wednesday, April 15, 2020

Django How to Use Bootstrap 4 Forms using Django Crispy Forms module


Django How to Use Bootstrap 4 Forms using Django Crispy Forms module

Crispy-forms is a great application that gives you control over how you render Django forms, without breaking the default behavior.

Install it using pip:

pip install django-crispy-forms

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
    'crispy_forms',

]

CRISPY_TEMPLATE_PACK = 'bootstrap4'
#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")  
    bio       = models.TextField(blank=True) 	
    file      = models.FileField() # for creating file input  
  
    class Meta:  
        db_table = "student"
#views.py
from django.shortcuts import render  
from myapp.forms import StudentForm #forms.py
from django.http import HttpResponse 
from myapp.functions import handle_uploaded_file  #functions.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("Record successfuly added")  
    else:  
        student = StudentForm()  
        return render(request,"student_form.html",{'form':student})  
#forms.py
from django import forms 
from myapp.models import StudentForm  #models.py
    
class StudentForm(forms.ModelForm):  
    class Meta:  
        model = StudentForm  
        fields = "__all__"
//templates/student_form.html
{% extends 'base.html' %}

{% load crispy_forms_tags %}

{% block content %}
  <form method="POST" class="post-form" enctype="multipart/form-data">
    {% csrf_token %}
	<!-- {{ form|crispy }} -->
    <div class="row">
      <div class="col-6">
        {{ form.firstname|as_crispy_field }}
      </div>
      <div class="col-6">
        {{ form.lastname|as_crispy_field }}
      </div>
    </div>
    {{ form.email|as_crispy_field }}
    {{ form.bio|as_crispy_field }}
    {{ form.file|as_crispy_field }}
    <button type="submit" class="btn btn-success">Save Student</button>
  </form>
{% endblock %}
//templates/base.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <title>Django Student</title>
  </head>
  <body>
    <div class="container">
      <div class="row justify-content-center">
        <div class="col-md-8">
          <h1 class="mt-2">Django Student</h1>
          <h3>Django How to Use Bootstrap 4 Forms using Django Crispy Forms module</h3>
          <hr class="mt-0 mb-4">
          {% block content %}
          {% endblock %}
        </div>
      </div>
    </div>
  </body>
</html>
#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)  
#urls.py
from django.contrib import admin  
from django.urls import path  
from myapp import views  

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

CREATE TABLE student (
id INTEGER PRIMARY KEY,
firstname STRING (50),
lastname STRING (50),
email STRING (50),
file STRING (255),
bio TEXT
);

Tuesday, April 14, 2020

Django - Create User Sign Up


Django - Create User Sign Up


 
#views.py
from django.shortcuts import render, redirect  

# Create your views here.   
from django.contrib.auth import login, authenticate
from myapp.forms import SignUpForm

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('/')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})
 
def home(request):
    return render(request, 'home.html')
 
#forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )
 
#urls.py
from django.contrib import admin  
from django.urls import path  
from myapp import views  

urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('signup', views.signup),
    path('', views.home),
]  
<!DOCTYPE html> <html lang="en">
//templates/signup.html
<head>  
<meta charset="UTF-8">  
<title>Django - Create User Sign Up</title> 
</head> 
<body>
<div class="container">
 <div class="row">
  <div class="col-md-12">
        <h2>Django - Create User Sign Up</h2> 
  <form method="post">
    {% csrf_token %}
  <!-- {{ form.as_p }} -->
    {% for field in form %}
      <p>
        {{ field.label_tag }}<br>
        {{ field }}
        {% if field.help_text %}
          <small style="color: grey">{{ field.help_text }}</small>
        {% endif %}
        {% for error in field.errors %}
          <p style="color: red">{{ error }}</p>
        {% endfor %}
      </p>
    {% endfor %}
    <button type="submit">Sign up</button>
  </form>
  
 </div> 
 </div> 
</div> 
</body> 
</html>

Monday, April 13, 2020

Django - How to Paginate with Django and Bootstrap


Django - How to Paginate with Django and Bootstrap


 
#views.py
from django.shortcuts import render, redirect  
from myapp.models import Employee  #models.py

# Create your views here.   
from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def index(request):
    user_list = User.objects.all()
    page = request.GET.get('page', 1)

    paginator = Paginator(user_list, 3)
    try:
        users = paginator.page(page)
    except PageNotAnInteger:
        users = paginator.page(1)
    except EmptyPage:
        users = paginator.page(paginator.num_pages)

    return render(request, 'user_list.html', { 'users': users })

def emp(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, 'emp_list.html', { 'employees': employees })
 
#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),
    path('emp', views.emp),
]  
 
#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" 
//templates/user_list.html
<!DOCTYPE html>  
<html lang="en">  
<head>  
<meta charset="UTF-8">  
<title>Django - How to Paginate with Django and Bootstrap</title> 
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head> 
<body>
<div class="container">
 <div class="row">
  <div class="col-md-12">
        <h4>Django - How to Paginate with Django and Bootstrap</h4>  
    <table id="bootstrapdatatable" class="table table-striped table-bordered" width="100%">
    <thead>
   <tr>
     <th>Username</th>
     <th>First name</th>
     <th>Last name</th>
     <th>Email</th>
   </tr>
    </thead>
    <tbody>
   {% for user in users %}
     <tr>
    <td>{{ user.username }}</td>
    <td>{{ user.first_name }}</td>
    <td>{{ user.last_name }}</td>
    <td>{{ user.email }}</td>
     </tr>
   {% endfor %}
    </tbody>
  </table>

  {% if users.has_other_pages %}
    <ul class="pagination">
   {% if users.has_previous %}
     <li><a href="?page={{ users.previous_page_number }}">«</a></li>
   {% else %}
     <li class="disabled"><span>«</span></li>
   {% endif %}
   {% for i in users.paginator.page_range %}
     {% if users.number == i %}
    <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
     {% else %}
    <li><a href="?page={{ i }}">{{ i }}</a></li>
     {% endif %}
   {% endfor %}
   {% if users.has_next %}
     <li><a href="?page={{ users.next_page_number }}">»</a></li>
   {% else %}
     <li class="disabled"><span>»</span></li>
   {% endif %}
    </ul>
  {% endif %}
  
 </div> 
 </div> 
</div> 
</body> 
</html>
//templates/emp_list.html
<!DOCTYPE html>  
<html lang="en">  
<head>  
<meta charset="UTF-8">  
<title>Django - How to Paginate with Django and Bootstrap</title> 
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head> 
<body>
<div class="container">
 <div class="row">
  <div class="col-md-12">
        <h4>Django - How to Paginate with Django and Bootstrap</h4>  
        <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>

  {% if employees.has_other_pages %}
    <ul class="pagination">
   {% if employees.has_previous %}
     <li><a href="?page={{ employees.previous_page_number }}">«</a></li>
   {% else %}
     <li class="disabled"><span>«</span></li>
   {% endif %}
   {% for i in employees.paginator.page_range %}
     {% if employees.number == i %}
    <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
     {% else %}
    <li><a href="?page={{ i }}">{{ i }}</a></li>
     {% endif %}
   {% endfor %}
   {% if employees.has_next %}
     <li><a href="?page={{ emplist.next_page_number }}">»</a></li>
   {% else %}
     <li class="disabled"><span>»</span></li>
   {% endif %}
    </ul>
  {% endif %}
  
 </div> 
 </div> 
</div> 
</body> 
</html>

Django CRUD (Create Read Update Delete) Example - Bootstrap Datatable


Django CRUD (Create Read Update Delete) Example - Bootstrap Datatable

CREATE TABLE employee (
id INTEGER PRIMARY KEY,
name STRING (100),
contact STRING (100),
email STRING (255)

);


models.py
 
#models.py
class Employee(models.Model):  
    name = models.CharField(max_length=100)  
    email = models.EmailField()  
    contact = models.CharField(max_length=15) 
 
    class Meta:  
        db_table = "employee" 
forms.py
 
#forms.py
from django import forms  
from myapp.models import Employee  
class EmployeeForm(forms.ModelForm):  
    class Meta:  
        model = Employee  
        fields = ['name', 'contact', 'email'] #https://docs.djangoproject.com/en/3.0/ref/forms/widgets/
        widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control' }), 
            'email': forms.EmailInput(attrs={ 'class': 'form-control' }),
            'contact': forms.TextInput(attrs={ 'class': 'form-control' }),
      }
views.py
 
#views.py
from django.shortcuts import render, redirect  
from myapp.forms import EmployeeForm  
from myapp.models import Employee  
# Create your views here.  
def addnew(request):  
    if request.method == "POST":  
        form = EmployeeForm(request.POST)  
        if form.is_valid():  
            try:  
                form.save()  
                return redirect('/')  
            except:  
                pass  
    else:  
        form = EmployeeForm()  
    return render(request,'index.html',{'form':form})  
def index(request):  
    employees = Employee.objects.all()  
    return render(request,"show.html",{'employees':employees})  
def edit(request, id):  
    employee = Employee.objects.get(id=id)  
    return render(request,'edit.html', {'employee':employee})  
def update(request, id):  
    employee = Employee.objects.get(id=id)  
    form = EmployeeForm(request.POST, instance = employee)  
    if form.is_valid():  
        form.save()  
        return redirect("/")  
    return render(request, 'edit.html', {'employee': employee})  
def destroy(request, id):  
    employee = Employee.objects.get(id=id)  
    employee.delete()  
    return redirect("/")  
urls.py
 
#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),  
    path('addnew',views.addnew),  
    path('edit/<int:id>', views.edit),  
    path('update/<int:id>', views.update),  
    path('delete/<int:id>', views.destroy),  
]  
templates/show.html
//templates/show.html
{% extends "base.html" %}

{% block title %}Employee Records{% endblock title %}

{% block content %}
 <div class="col-md-12">
        <h4>Django CRUD (Create Read Update Delete) Example - Bootstrap Datatable</h4> <span><a href="/addnew" class="btn btn-primary">Add New Record</a></span>  
        <div class="table-responsive">
  <table id="bootstrapdatatable" class="table table-striped table-bordered" width="100%">
            <thead>
                <th><input type="checkbox" id="checkall" /></th>
                <th>ID</th>
                <th>Employee Name</th>
                <th>Employee Email</th>
                <th>Employee Contact</th>
                <th>Edit</th>
                <th>Delete</th>
             </thead>
   <tbody>
   {% for employee in employees %}  
    <tr>  
     <td><input type="checkbox" class="checkthis" /></td>
     <td>{{ employee.id }}</td>  
     <td>{{ employee.name }}</td>  
     <td>{{ employee.email }}</td>  
     <td>{{ employee.contact }}</td>  
     <td><p data-placement="top" data-toggle="tooltip" title="Edit"><a href="/edit/{{ employee.id }}" class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit" ><span class="glyphicon glyphicon-pencil"></span></a></p></td>
     <td><p data-placement="top" data-toggle="tooltip" title="Delete"><a href="/delete/{{ employee.id }}" class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete" ><span class="glyphicon glyphicon-trash"></span></a></p></td>  
    </tr>  
   {% endfor %} 
   </tbody>
        
  </table>
        </div>
    </div>
{% endblock content %}
templates/base.html
//templates/base.html
<!DOCTYPE html>  
<html lang="en">  
<head>  
<meta charset="UTF-8">  
<title>{% block title %}{% endblock %}</title>
{% load static %}  
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>

<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
</head> 
<body>
<div class="container">
 <div class="row">
    {% block content %}{% endblock %}
 </div>
</div>
<script>
$(document).ready(function() {
    $('#bootstrapdatatable').DataTable({     
      "aLengthMenu": [[3, 5, 10, 25, -1], [3, 5, 10, 25, "All"]],
        "iDisplayLength": 3
       } 
    );
} );
</script>
</body> 
</html>
templates/index.html
//templates/index.html
{% extends "base.html" %}

{% block title %}Add New Employee Records{% endblock title %}

{% block content %}
<div class="col-md-12">
    <h4>Django CRUD (Create Read Update Delete) Example - Bootstrap Datatable</h4> 
        
 <form method="POST" class="post-form" action="/addnew">  
   {% csrf_token %}  
  <div class="container">  
 <br>  
  <div class="form-group row">  
  <label class="col-sm-1 col-form-label"></label>  
  <div class="col-sm-4">  
  <h3>Enter Details</h3>  
  </div>  
   </div>  
  
   <div class="form-group row">  
  <label class="col-sm-2 col-form-label">Employee Name:</label>  
  <div class="col-sm-4">  
    {{ form.name }}  
  </div>  
   </div>  
  <div class="form-group row">  
  <label class="col-sm-2 col-form-label">Employee Email:</label>  
  <div class="col-sm-4">  
    {{ form.email }}  
  </div>  
   </div>  
  <div class="form-group row">  
  <label class="col-sm-2 col-form-label">Employee Contact:</label>  
  <div class="col-sm-4">  
    {{ form.contact }}  
  </div>  
   </div>  
  <div class="form-group row">  
  <label class="col-sm-1 col-form-label"></label>  
  <div class="col-sm-4">  
  <button type="submit" class="btn btn-primary">Submit</button>  
  </div>  
   </div>  
  </div>  
 </form>  
</div> 
{% endblock content %} 
templates/edit.html
//templates/edit.html
{% extends "base.html" %}

{% block title %}Add New Employee Records{% endblock title %}

{% block content %}
<div class="col-md-12">
    <h4>Django CRUD (Create Read Update Delete) Example - Bootstrap Datatable</h4>  
 <form method="POST" class="post-form" action="/update/{{employee.id}}">  
   {% csrf_token %}  
  <div class="container">  
 <br>  
  <div class="form-group row">  
  <label class="col-sm-1 col-form-label"></label>  
  <div class="col-sm-4">  
  <h3>Update Details</h3>  
  </div>  
   </div>  
  <div class="form-group row">  
  <label class="col-sm-2 col-form-label">Employee Id:</label>  
  <div class="col-sm-4">  
   <input type="text" class="form-control" name="id" id="id_id" required maxlength="20" value="{{ employee.id }}"/>  
  </div>  
   </div>  
   <div class="form-group row">  
  <label class="col-sm-2 col-form-label">Employee Name:</label>  
  <div class="col-sm-4">  
   <input type="text" class="form-control" name="name" id="id_name" required maxlength="100" value="{{ employee.name }}" />  
  </div>  
   </div>  
  <div class="form-group row">  
  <label class="col-sm-2 col-form-label">Employee Email:</label>  
  <div class="col-sm-4">  
   <input type="email" class="form-control" name="email" id="id_email" required maxlength="254" value="{{ employee.email }}" />  
  </div>  
   </div>  
  <div class="form-group row">  
  <label class="col-sm-2 col-form-label">Employee Contact:</label>  
  <div class="col-sm-4">  
   <input type="text" class="form-control" name="contact" id="id_contact" required maxlength="15" value="{{ employee.contact }}" />  
  </div>  
   </div>  
  <div class="form-group row">  
  <label class="col-sm-1 col-form-label"></label>  
  <div class="col-sm-4">  
  <button type="submit" class="btn btn-success btn-lg">Update</button>  
  </div>  
   </div>  
  </div>  
 </form>  
{% endblock content %}   

Sunday, April 12, 2020

Django Admin CRUD (Create Read Update Delete)


Django Admin CRUD (Create Read Update Delete)



 
#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" 
  
class Employee(models.Model):  
    name = models.CharField(max_length=100)  
    contact = models.CharField(max_length=100)  
    class Meta:  
        db_table = "employee" 
 
#admin.py
from django.contrib import admin

# Register your models here.
from myapp.models import StudentForm, Employee  
admin.site.register(StudentForm) # StudentForm is registered  
admin.site.register(Employee) # Employee is registered  

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

http://127.0.0.1:8000/admin/

Django File Upload and save data to database sqlite3


Django File Upload and save data to database sqlite3

Django provides built-in library and methods that help to upload a file to the server.

The forms.FileField() method is used to create a file input and submit the file to the server. While working with files, make sure the HTML form tag contains enctype="multipart/form-data" property.
 
#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" 
 
#forms.py
from django import forms  
from myapp.models import StudentForm  #models.py
   
class StudentForm(forms.ModelForm):  
    class Meta:  
        model = StudentForm  
        fields = "__all__" 
 
#view.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})  
//templates/index.html
<html>
<head>
<title>Django File Upload</title>
</head>
<body>
<p><h1>Django File Upload</h1></p>
<form method="POST" class="post-form" enctype="multipart/form-data">  
        {% csrf_token %}  
        {{ form.as_p }}  
        <button type="submit" class="save btn btn-default">Save</button>  
</form>  
</body>  
</html>
 
#urls.py
from django.contrib import admin  
from django.urls import path  
from myapp import views  
urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('index/', views.index),  
] 
 
#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)  

Saturday, April 11, 2020

Contact Us - Python Django Forms and Validation


Contact Us - Python Django Forms and Validation


 
#contact.py
from django import forms
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.mail import send_mail, get_connection

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100, label='Your Name', widget=forms.TextInput(attrs={ 'class': 'form-control' }))
    email = forms.EmailField(label='Your e-mail address', widget=forms.TextInput(attrs={ 'class': 'form-control' }))
    subject = forms.CharField(max_length=100, widget=forms.TextInput(attrs={ 'class': 'form-control' }))
    message = forms.CharField(required=False, widget=forms.Textarea(attrs={ 'class': 'form-control' }))
 
def contact(request):
    submitted = False
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
             # assert False
            con = get_connection('django.core.mail.backends.console.EmailBackend')
            send_mail(
                cd['subject'],
                cd['message'],
                cd.get('email', 'noreply@example.com'),
                ['cairocoders0711@gmail.com'],
                connection=con
             )
            return HttpResponseRedirect('/contact?submitted=True')
    else:
        form = ContactForm()
        if 'submitted' in request.GET:
            submitted = True

    return render(request, 'contact/contact.html', {'form': form, 'submitted': submitted})

def index(request):
    return render(request, "index.html")
 
#urls.py
from django.contrib import admin
from django.urls import include, path
from django.contrib.auth import views as auth_views
from myapp import contact

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

{% block title %}Contact Us{% endblock title %}

{% block content %}
    <div class="section-content">
  <h1 class="section-header">Get in <span class="content-header wow fadeIn " data-wow-delay="0.2s" data-wow-duration="2s"> Touch with us</span></h1>
  <h3>Lorem Ipsum is simply dummy text of the printing and typesetting industry</h3>
 </div>
 {% if submitted %}
 <div class="alert alert-success" role="alert">
   Your message was submitted successfully. Thank you.
 </div>
 {% else %}
 
  {% if form.errors %}
   {% for error in form.errors %} 
     <div class="alert alert-danger" role="alert">
      This fields is required : {{ error }}
    </div>
   {% endfor %}
  {% endif %} 
  
 <form action="" method="post" novalidate>
  <div class="col-md-6 form-line">
   <div class="form-group">
    <label for="exampleInputUsername">Your name</label>
    {{ form.name }}
   </div>
   <div class="form-group">
    <label for="exampleInputEmail">Email Address</label>
    {{ form.email }}
   </div> 
   <div class="form-group">
    <label for="telephone">Subject</label>
    {{ form.subject }}
   </div>
  </div>
  <div class="col-md-6">
   <div class="form-group">
      <label for ="description"> Message</label>
      {{ form.message }}
   </div>
   <div>
    <button type="submit" value="Submit" class="btn btn-default submit"><i class="fa fa-paper-plane" aria-hidden="true"></i>  Send Message</button>
   </div>    
  </div>
     {% csrf_token %}
     </form>
 {% endif %}
{% endblock content %}
//templates/base.html
<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>{% block title %}{% endblock %}</title>   
 {% load static %} 
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
 <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>

    <link href="https://fonts.googleapis.com/css?family=Oleo+Script:400,700" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Teko:400,700" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
 
 <link href="{% static 'css/style.css' %}" rel="stylesheet"> 
</head>  
<body>
<nav class="navbar navbar-inverse">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">Cairocoders</a>
    </div>
    <ul class="nav navbar-nav">
      <li class="active"><a href="/">Home</a></li>
      <li><a href="/calendar">Calendar</a></li>
      <li><a href="/about">About Us</a></li>
      <li><a href="/contact">Contact Us</a></li>
    </ul>
  </div>
</nav>
  
    <header class="text-white">
    <div class="container text-center">
      <h1>Contact Us - Python Django Forms and Validation</h1>
      <p class="lead">Contact Us - Python Django Forms and Validation</p>
    </div>
  </header>
  
 <section id="contact">
   <div class="contact-section">
   <div class="container">
   {% block content %}
            {% endblock %}
   </div>
   </div>
 </section>
</body> 
</html>
//templates/index.html
{% extends "base.html" %}

{% block title %}Home{% endblock title %}

{% block content %}
Homepage
{% endblock content %}
/* static/css/style.css */
ul.errorlist {
    margin: 0;
    padding: 0;
}
.errorlist li {
    border: 1px solid red;
    color: red;
    background: rgba(255, 0, 0, 0.15);
    list-style-position: inside;
    display: block;
    font-size: 1.2em;
    margin: 0 0 3px;
    padding: 4px 5px;
    text-align: center;    
    border-radius: 3px;
}
.success {
    background-color: rgba(0, 128, 0, 0.15);
    padding: 10px;
    text-align: center;
    color: green;
    border: 1px solid green;
    border-radius: 3px;
}

/*Contact sectiom*/
.content-header{
  font-family: 'Oleo Script', cursive;
  color:#fcc500;
  font-size: 45px;
}
.section-content{
  text-align: center; 
}
#contact{
  font-family: 'Teko', sans-serif;
  padding-top: 60px;
  width: 100%;
  background: #3a6186; /* fallback for old browsers */
  background: -webkit-linear-gradient(to left, #3a6186 , #89253e); /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to left, #3a6186 , #89253e); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
    color : #fff;    
}
.contact-section{
  padding-top: 40px;
}
.contact-section .col-md-6{
  width: 50%;
}
.form-line{
  border-right: 1px solid #B29999;
}
.form-group{
  margin-top: 10px;
}
label{
  font-size: 1.3em;
  line-height: 1em;
  font-weight: normal;
}
.form-control{
  font-size: 1.3em;
  color: #080808;
}
textarea.form-control {
    height: 135px;
   /* margin-top: px;*/
}
.submit{
  font-size: 1.1em;
  float: right;
  width: 150px;
  background-color: transparent;
  color: #fff;
}

Related Post