Category

Category: Python

Performing CRUD Operations with Sessions in Python – Django

Setting Up Sessions


In Django, you can enable sessions from the settings.py by adding some lines to the MIDDLEWARE and the INSTALLED_APPS options.

MIDDLEWARE should have −

‘django.contrib.sessions.middleware.SessionMiddleware’

And INSTALLED_APPS should have −

‘django.contrib.sessions’

By default, Django saves session information in database (django_session table or collection), but you can configure the engine to store information using other ways like: in file or in cache.

CRUD Operations


Read

item_id = str(1)
cart_items = request.session

# Create an empty cart object if it does not exist yet 
if not cart_items.has_key("cart"):
	cart_items["cart"] = {}

# Retrieve single item by key 
cart_items.get(item_id)

# Retrieve all 
cart_items.items()

Add

item_id = str(1)
cart_items = request.session

# Create an empty cart object if it does not exist yet 
if not cart_items.has_key("cart"):
	cart_items["cart"] = {}

product_data = {
	'quantity': 2,
	'date_added': strftime("%Y-%m-%d %H:%M:%S", gmtime())
}

cart_items["cart"][item_id] = product_data
cart_items.modified = True

Edit

item_id = str(1)
cart_items = request.session

# Create an empty cart object if it does not exist yet 
if not cart_items.has_key("cart"):
	cart_items["cart"] = {}

# Edit quantity of item ID: 1 
cart_items["cart"][item_id]["quantity"]  = 3
cart_items.modified = True

Delete

item_id = str(1)
cart_items = request.session

# Create an empty cart object if it does not exist yet 
if not cart_items.has_key("cart"):
	cart_items["cart"] = {}

# Delete an item
try:
	del cart_items["cart"][item_id]
except KeyError:
	pass
cart_items.modified = True

Python – Django AJAX Pagination with Search and Sort

In this tutorial, we are going to build a simple AJAX Pagination with search and sort using Python with Django framework. This tutorial assumes that you already have an existing Module built using the latest Django framework. What you see in the above picture is exactly what we are going to build out. So let’s get started.

Requirements :

  1. Download and install the latest version of python (version 3+) from here: https://www.python.org/downloads/
    • For Mac users: Python version 2.7+ is installed by default, so to use python version 3, you will have to use these commands:
      • python3 <command>
      • pip3 <command>
  2. Install django using pip:

Integrating the AJAX Pagination with Search and Sort :

Create the base template mymodule/templates/mymodule/base.html with the following contents:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>MyDjangoApp</title>
    
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  	<link rel="stylesheet" href="{% static 'ecommerce/css/styles.css' %}" />
</head>
<body class="override">
    <nav class="navbar navbar-inverse" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="/mymodule/">Django Pagination</a>
            </div>
        </div>
    </nav>
    
    <div class="container">
        <div class="row">
            {% block content %}{% endblock %}
        </div>
    </div>
  	<script src="{% static 'mymodule/js/app.js' %}"></script>
</body>
</html>

Then create the products template: mymodule/templates/mymodule/products.html and include the code bellow:

{% extends "mymodule/base.html" %}
 
{% block content %}
	<div class="container products-view-user">
		{% csrf_token %}
		<form class = "post-list">
			<input type = "hidden" value = "" />
		</form>
		
		<article class="navbar-form navbar-left p-0 m-0 ml-b">
			<div class="form-group">
				<label>Per Page: </label>
				<select class="form-control post_max">
					<option value="1">1</option>
					<option value="2">2</option>
					<option value="3">3</option>
				</select>
				<label>Search Keyword: </label>
				<input type="text" class="form-control post_search_text" placeholder="Enter a keyword">
			</div>
			<input type = "submit" value = "Filter" class = "btn btn-primary post_search_submit" />
		</article>
		
		<a href="user-products-add.php" class="btn btn-success pull-right">Add New</a>
		
		<br class = "clear" />
		
		<div class = "wave-box-wrapper">
			<div class = "wave-box"></div>
			<table class = "table table-striped table-post-list no-margin">
				<thead>
					<tr>
						<th>Image</th>
						<th id = "name" class = "active"><a href = "#">Name</a></th>
						<th id = "price"><a href = "#">Price</a></th>
						<th id = "status"><a href = "#">Status</a></th>
						<th id = "date"><a href = "#">Date</a></th>
						<th id = "quantity"><a href = "#">Quantity</a></th>
						<th>Action</th>
					</tr>
				</thead>
				<tbody class = "pagination-container"></tbody>
			</table>
			
			<div class = "pagination-nav"></div>
		</div>
	</div>
{% endblock %}

Create the controller that will handle both GET and POST methods to the products page. The code bellow goes to your mymodule/views.py ….

Click here to download the FULL tutorial

 

 

Creating a Registration Page in Django

In this tutorial we are going to build a simple registrtaion using Django Framework. Above photo is exactly how our app will look like when completed, so let’s get started.

Note: The codes in this tuturial was developed using Django v1.10.6, it may not work with older versions.

Create the base template mymodule/templates/mymodule/base.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html>
<html lang="en">
<head>
    <title>MyDjangoApp</title>
   
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
   
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body class="override">
    <nav class="navbar navbar-inverse" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="/mymodule/">MyDjangoApp</a>
            </div>
           
            <div id="navbar" class="collapse navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="/mymodule/register">Register</a></li>
                </ul>
            </div>
        </div>
    </nav>
   
    <div class="container">
        <div class="row">
            {% block content %}{% endblock %}
        </div>
    </div>
   
    <footer>
        <div class="container">
            <div class="row well ml-t">
                <div class="col-lg-8 col-md-8">    
                    <h4>Developed by: <a href="https://carlofontanos.com" target="_blank">Carl Victor C. Fontanos</a></h4>
                </div>
                <div class="col-lg-4 col-md-4">
                    <p class="m-t">Copyright &copy <a href="https://carlofontanos.com" target="_blank">www.carlofontanos.com</a> 2017</p>
                    <p>All Rights Reserved.</p>
                </div>
            </div>
        </div>
    </footer>
</body>
</html>

Then create the registration template: mymodule/templates/mymodule/register.html and include the code bellow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
{% extends "mymodule/base.html" %}

{% block content %}
    <div class="container">
        <form action="{% url 'mymodule:user_register' %}" method="post">
            {% csrf_token %}
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Register</div>
                    <div class="panel-body">
                        {% if error_message %}
                            <p class="bg-danger p-d ml-b">{{ error_message }}</p>
                        {% endif %}
                       
                        <div class="form-group clearfix">
                            <label for="{{ form.username.id_for_label }}" class="col-md-4 control-label text-right">Username<span class="text-red">*</span>:</label>
                            <div class="col-md-6">
                                {{ form.username }}
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <label for="{{ form.email.id_for_label }}" class="col-md-4 control-label text-right">Email<span class="text-red">*</span>:</label>
                            <div class="col-md-6">
                                {{ form.email }}
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <label for="{{ form.password.id_for_label }}" class="col-md-4 control-label text-right">Password<span class="text-red">*</span>:</label>
                            <div class="col-md-6">
                                {{ form.password }}
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <label for="{{ form.password_repeat.id_for_label }}" class="col-md-4 control-label text-right">Confirm password:</label>
                            <div class="col-md-6">
                                {{ form.password_repeat }}
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <label for="{{ form.first_name.id_for_label }}" class="col-md-4 control-label text-right">First Name:</label>
                            <div class="col-md-6">
                                {{ form.first_name }}
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <label for="{{ form.last_name.id_for_label }}" class="col-md-4 control-label text-right">Last Name:</label>
                            <div class="col-md-6">
                                {{ form.last_name }}
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <label for="{{ form.phone_number.id_for_label }}" class="col-md-4 control-label text-right">Phone Number:</label>
                            <div class="col-md-6">
                                {{ form.phone_number }}
                            </div>
                        </div>
                        <div class="col-md-6 col-md-offset-4">
                            <input type="submit" value="Register" class="btn btn-success">
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
{% endblock %}

Create a new file forms.py and place it under mymodule/ directory. In it, include the following field definitions:

1
2
3
4
5
6
7
8
9
10
from django import forms

class RegisterForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}))
    password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}))
    password_repeat = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}))
    first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    phone_number = forms.CharField(widget=forms.NumberInput(attrs={'class':'form-control'}), required=False)

Create the controller that will handle both GET and POST methods to the registration form. The code bellow goes to your mymodule/views.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from django.contrib.auth.models import User
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import RegisterForm

def user_register(request):
    # if this is a POST request we need to process the form data
    template = 'mymodule/register.html'
   
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = RegisterForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            if User.objects.filter(username=form.cleaned_data['username']).exists():
                return render(request, template, {
                    'form': form,
                    'error_message': 'Username already exists.'
                })
            elif User.objects.filter(email=form.cleaned_data['email']).exists():
                return render(request, template, {
                    'form': form,
                    'error_message': 'Email already exists.'
                })
            elif form.cleaned_data['password'] != form.cleaned_data['password_repeat']:
                return render(request, template, {
                    'form': form,
                    'error_message': 'Passwords do not match.'
                })
            else:
                # Create the user:
                user = User.objects.create_user(
                    form.cleaned_data['username'],
                    form.cleaned_data['email'],
                    form.cleaned_data['password']
                )
                user.first_name = form.cleaned_data['first_name']
                user.last_name = form.cleaned_data['last_name']
                user.phone_number = form.cleaned_data['phone_number']
                user.save()
               
                # Login the user
                login(request, user)
               
                # redirect to accounts page:
                return HttpResponseRedirect('/mymodule/account')

   # No post data availabe, let's just show the page.
    else:
        form = RegisterForm()

    return render(request, template, {'form': form})

Finally, register the view in our mymodule/urls.py:

1
2
3
4
5
6
7
from django.conf.urls import url
from . import views

app_name = 'mymodule' # So we can use it like: {% url 'mymodule:user_register' %} on our template.
urlpatterns = [
    url(r'^register/$', views.user_register, name='user_register')
]