You are on page 1of 28

1. We need to create a Django app. In this example, I will name the app stockmgmt.

Meaning stock management system

python manage.py startapp stockmgmt

2. Expand your project “djangoproject“, open “settings.py” and add the app name
“stockmgmt” you created in step 1 above to “INSTALLED_APPS“. This will allow us to
manage the database of the app with Django commands such as makemigrations, migrate
etc.
Your installed app section should look like this:

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

3. We need to create a table where the stock data will be saved. Below is the table
structure. This will be modified as we progress into the tutorial. Add this code to
models.py

class Stock(models.Model):
category = models.CharField(max_length=50, blank=True, null=True)
item_name = models.CharField(max_length=50, blank=True, null=True)
quantity = models.IntegerField(default='0', blank=True, null=True)
receive_quantity = models.IntegerField(default='0', blank=True, null=True)
receive_by = models.CharField(max_length=50, blank=True, null=True)
issue_quantity = models.IntegerField(default='0', blank=True, null=True)
issue_by = models.CharField(max_length=50, blank=True, null=True)
issue_to = models.CharField(max_length=50, blank=True, null=True)
phone_number = models.CharField(max_length=50, blank=True, null=True)
created_by = models.CharField(max_length=50, blank=True, null=True)
reorder_level = models.IntegerField(default='0', blank=True, null=True)
last_updated = models.DateTimeField(auto_now_add=False, auto_now=True)
export_to_CSV = models.BooleanField(default=False)

def __str__(self):
return self.item_name

4. Run the following commands for the tables to be created in the database

Prepare the model to be created as a table in the database


python manage.py makemigrations

Next, create the prepared model above as a table in the database


python manage.py migrate

5. Register the model in admin so that we can insert data into the database table
from .models import Stock

admin.site.register(Stock)

1. Create a forms.py module in stockmgmgt app folder

2. In the form.py module, import django model form


from django import forms
In the same form.py module, import the Stock model from model.py
from .models import Stock

3. Create a model form in forms.py. Name the form StockCreateform as shown below

class StockCreateForm(forms.ModelForm):
class Meta:
model = Stock
fields = ['category', 'item_name', 'quantity']

4. In admin.py, import the StockCreateForm created in step 3 above


from .forms import StockCreateForm

Next, create a class, name it StockCreateAdmin, with list_display, form,


list_filter, and search_field as shown below.

class StockCreateAdmin(admin.ModelAdmin):
list_display = ['category', 'item_name', 'quantity']
form = StockCreateForm
list_filter = ['category']
search_fields = ['category', 'item_name']

5. Modify your registration to apply the customization as below.

admin.site.register(Stock, StockCreateAdmin)

1. Create a templates folder in stockmgmgt app where all HTML pages will be saved.

2. Create a home.html in the templates folder and add some text you want to display

3. In views.py is where you define what will be displayed when a user navigates to
a URL.
def home(request):
title = 'Welcome: This is the Home Page'
context = {
"title": title,
}
return render(request, "home.html",context)
4. Add a path / url for home page

from stockmgmgt import views

urlpatterns = [
---
path('', views.home, name='home'),
---
5. Now go to localhost:8000 to view your beautify work

1. Create a html page and save it as list_item.html

<!DOCTYPE html>
<html>
<head>
<title>Item List</title>
</head>
<body>
{{title}}<br>
{% for instance in queryset %}
{{instance.item_name}}, {{instance.quantity}}<br>

{% endfor %}

</body>
</html>

2. Make a view for listing the items from the database

def list_item(request):
title = 'List of Items'
queryset = Stock.objects.all()
context = {
"title": title,
"queryset": queryset,
}
return render(request, "list_item.html", context)
3. Add the URL

path('list_item/', views.list_item, name='list_item'),

1. Make a view for saving items in the database

def add_items(request):
form = StockCreateForm(request.POST or None)
if form.is_valid():
form.save()
context = {
"form": form,
"title": "Add Item",
}
return render(request, "add_items.html", context)
2. Add the URL

path('add_items/', views.add_items, name='add_items'),


3. Create a html page and save it as add_item.html

<!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
</head>
<body>
<form method='POST' action=''>{% csrf_token %}
{{form}}
<input type="submit" value='Save'/>
</form>

</body>
</html>

Import render redirect to allow you the page to be redirected to another after
saving the data.

from django.shortcuts import render, redirect


Add return redirect immediately after form.save()

if form.is_valid():
form.save()
return redirect('/list_items')

1. Create a folder called static in the django application folder

2. Create css, js and img folders inside static folder created in the point above

3. Create a file names stylesheet.css in CSS folder created above and paste in the
following:

body {
background-color: #34eb6b;
}
4. Load static in your HTML documents
{% load staticfiles %}

5. In the header tag of HTML document, add the following


<link href="{% static 'css/stylesheet.css' %}" rel="stylesheet">

11-how-to-add-boostrap-to-django-without-cdn/

1. Download or copy the content of the bootstrap template you want to use from this
following URL: https://getbootstrap.com/docs/4.4/examples/

1. Click on one example: We will use (Navbar Fixed),

2. Right-click on the page and select view page source and save/copy the content in
your template folder and name it home.html.

3. Load the static files with {% load staticfiles %} in the page.

4. Download all CSS, JS associated with the bootstrap framework you are using into
your CSS, JS folder.
Example:
bootstrap.min.css, navbar-fixed-top.css

5. Use the following to link css to your page:


<link href="{% static 'css/fileName.css' %}" rel="stylesheet">

6. Use the following to link js files to your page:


<script src="{% static 'js/fileName.js' %}"></script>

12-how-to-add-bootstrap-to-django-using-cdn/
Got to https://getbootstrap.com/docs/4.4/getting-started/introduction/ and copy the
CDN for both the CSS and JS files to your HTML page

13-how-to-add-crispy-forms-to-django/
Crispy forms helps us style the input forms of our application with less code.

1. Install crispy-forms using the following command

pip install --upgrade django-crispy-forms

2. Add crispy_forms to INSTALLED_APPS in settings.py

INSTALLED_APPS = (

'crispy_forms',

)

3. Add CRISPY_TEMPLATE_PACK = 'bootstrap4' in settings.py


4. Add {% load crispy_forms_tags %} on top of the template that renders the form

5. Apply for styling style with the following

{{form|crispy}}

14-how-to-include-navbar-in-django/

1. Remove or just cut the navbar from all the pages. Usually from <nav> to </nav>

<nav ...>
</nav>
2. Create a new html page, name it navbar.html then paste in the content of navbar
content cut above

3. Above the body page, example home.html, add the following code to include the
navbar in the home page

{% include 'navbar.html' %}

15-how-to-list-items-in-a-table-in-django/

1. Open computer_list.html add class to the h1 tag of the title

<table class='table'>
<thead>
<tr>
<th>COUNT</th>
<th>CATEGORY</th>
<th>ITEM NAME</th>
<th>QUANTITY IN STORE</th>
</tr>
</thead>
{% for instance in queryset %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{instance.category}}</td>
<td>{{instance.item_name}}</td>
<td>{{instance.quantity}}</td>
</tr>
{% endfor %}
</table>

2. Open stylesheet.css
Update it with the following codes:

/*Align the title to the center of the page*/


.table{
font-size: 13px;
text-align: center;
width: 95%;
margin: auto;
text-align: center;
}

/*Make alternating colors for the table rows*/


.table tr:nth-child(odd){
background: #B8CAE4
}

.table tr:nth-child(even){
background: #dae5f4
}

th {
background-color: #337ab7;
color: white;
}

3. Create a <div> element to style the table container

<div class="display_table">
<table>
</table
</div><!--End of display table-->
4. Style the <div> element

.display_table{
border-bottom-right-radius: 20px;
/*border-bottom-left-radius: 20px;*/
padding-left: 5px;
padding-right: 5px;
padding-bottom: 20px;
box-shadow: 12px 12px 20px 6px #2e6da4;
}
5. Style the header text

<div class="header"{{header}}</div>
.header {
font-family: helvetica;
color: #337ab7;
font-size: 50px;
text-align: center;
width: 100%;
text-shadow: 6px 6px 6px #c9c6c6;
display: block;
font-weight: bolder;
}
6. Save and refresh the computer_list page

16-how-to-make-a-search-form-in-django/
1. Make a form in forms.py

class StockSearchForm(forms.ModelForm):
class Meta:
model = Stock
fields = ['category', 'item_name']
2. Import the form and add it to the view with a condition when to run the form

form = StockSearchForm(request.POST or None)


if request.method == 'POST':
queryset = Stock.objects.filter(category__icontains=form['category'].value(),

item_name__icontains=form['item_name'].value()
)
context = {
"form": form,
"header": header,
"queryset": queryset,
}
3. Add the form to the list_items.html tamplate

<form method='POST' action=''>{% csrf_token %}


{{form|crispy}}
<input type="submit" value='Search'/>
</form>
<br>

17-how-to-validate-and-prevent-duplicate-data-in-django-stock-management-system/
1. Open forms.py and validate the StockCreateForm

To prevent saving object with a blank item name

class StockCreateForm(forms.ModelForm):
class Meta:
model = Stock
fields = ['category', 'item_name', 'quantity']

def clean_category(self):
category = self.cleaned_data.get('category')
if not category:
raise forms.ValidationError('This field is required')
return category

def clean_item_name(self):
item_name = self.cleaned_data.get('item_name')
if not item_name:
raise forms.ValidationError('This field is required')
return item_name
2. Alerting and preventing the duplicate entry of computer name

for instance in Stock.objects.all():


if instance.category == category:
raise forms.ValidationError(str(category) + ' is already
created')
return category

18-how-to-update-data-in-django/

1. Create a form for updating data

class StockUpdateForm(forms.ModelForm):
class Meta:
model = Stock
fields = ['category', 'item_name', 'quantity']
2. Import the form created in step 1 then create a view to handle and process
update request.

def update_items(request, pk):


queryset = Stock.objects.get(id=pk)
form = StockUpdateForm(instance=queryset)
if request.method == 'POST':
form = StockUpdateForm(request.POST, instance=queryset)
if form.is_valid():
form.save()
return redirect('/list_items')

context = {
'form':form
}
return render(request, 'add_items.html', context)

3. Create a URL/PATH to pass the ID of the object to be updated

path('update_items/<str:pk>/', views.update_items, name="update_items"),

4. In the items_list page, and an anchor linked to the update URL/PATH

<td><a href="{% url 'update_items' instance.id %}">{{instance.item_name}}</a></td>

19-how-to-delete-data-in-django-with-confirm-delete-prompt/

1. Create a view to handle and process delete request.

def delete_items(request, pk):


queryset = Stock.objects.get(id=pk)
if request.method == 'POST':
queryset.delete()
return redirect('/list_items')
return render(request, 'delete_items.html')

2. Create a new template and add a form with a “confirm delete” button

<form method="post" action="">


{% csrf_token %}
<h1>Are you sure you want to delete?</h1><br>
<input class="btn btn-danger" type="submit" value="Yes" />
<a href="/list_items"><div class="btn btn-primary">Cancel</div></a>
</form>

3. Create a URL/PATH to pass the ID of the object to be deleted

path('delete_items/<str:pk>/', views.delete_items, name="delete_items"),

4. In the items_list page, add an anchor linked to the delete URL/PATH


<td><a href="{% url 'delete_items' instance.id %}">Delete</a></td>

20-how-to-add-a-choice-field-in-django/

1. Create a choice to of items.

category_choice = (
('Furniture', 'Furniture'),
('IT Equipment', 'IT Equipment'),
('Phone', 'Phone'),
)
category = models.CharField(max_length=50, blank=True, null=True,
choices=category_choice)

21-how-to-add-a-foreign-field-in-django/
1. Create a category model

class Category(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
def __str__(self):
return self.name
2. Make migration and migrate

3. If you have any data in the existing Stock table, you will need to insert some
data in the category table before proceeding

4. Update the Stock model. Change category from Charfield to ForeignKey

class Stock(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)

5. Chose a default ID for existing data in the Category table when prompted
(Usually when adding a new field to an existing table that has data)

22-how-to-export-data-to-csv-or-excel-in-django/

1. In forms.py, add a form field in the search form

export_to_CSV = forms.BooleanField()
2. In views.py, import HttpResponse from django.http, and csv

from django.http import HttpResponse


import csv
3. Make an if condition that will export data to CSV

if form['export_to_CSV'].value() == True:
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="List of
stock.csv"'
writer = csv.writer(response)
writer.writerow(['CATEGORY', 'ITEM NAME', 'QUANTITY'])
instance = queryset
for stock in instance:
writer.writerow([stock.category, stock.item_name,
stock.quantity])
return response

23-how-to-add-notification-in-django/
1. In views.py, import messages module

from django.contrib import messages


2. Paste the following code immediately below form.save()

messages.success(request, 'Successfully Saved')


3. Paste the code in the template where you want to display the message

{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif
%}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
4. Style the message

.success{
list-style: none;
background-color: #2e6da4;
color: white;
box-shadow: 12px 12px 12px #e61c66;
text-align: center;
}

24-how-to-add-work-with-a-datefield-in-django-stock-management-system/

Adding Data: If you want to automatically add a date and time in a field only when
adding an object for the first time in a Django App, set the auto_now_add=True.

...
datefield = models.DateTimeField(auto_now_add=True, auto_now=False)
...
Updating Data: If you want to add date and time only when the object is being
edited, set auto_now=True

...
datefield = models.DateTimeField(auto_now_add=False, auto_now=True)
...
If you want to add date and time while adding or updating data, set both
auto_now_add=True and auto_now=True

...
datefield = models.DateTimeField(auto_now_add=True, auto_now=True)
...
If you want to only user’s of the application to choose the date and time, then set
both auto_not_add=False and auto_now=False

...
datefield = models.DateTimeField(auto_now_add=False, auto_now=False)
...

25-how-to-make-a-detail-page-in-django-stock-management-system/

1. Make a template and name it stock_detail.html

<a href='#issue'><div class='btn btn-danger'>ISSUE THIS ITEM</div></a>


<a href='#receive'><div class='btn btn-primary'>RECEIVE THIS ITEM</div></a>
<br><br>
<div class="display_table">
<table class='table'>
<tr>
<th>ITEM NAME</th>
<th>QUANTITY IN STORE</th>
<th>LAST UPDATED</th>
<th>REORDER LEVEL</th>
</tr>
<tr>
<td>{{queryset.item_name}}</td>
<td>{{queryset.quantity}}</td>
<td>{{queryset.last_updated}}</td>
<td>{{queryset.reorder_level}}</td>
</tr>
</table>
</div>
2. Make a detail view

def stock_detail(request, pk):


queryset = Stock.objects.get(id=pk)
context = {
"title": queryset.item_name,
"queryset": queryset,
}
return render(request, "stock_detail.html", context)
3. Make a url to run the detail view

path('stock_detail/<str:pk>/', views.stock_detail, name="stock_detail"),


4. Make an anchor to link to the detail URL

<td><a href="{% url 'stock_detail' instance.id %}">{{instance.quantity}}</a></td>

26-updating-stock-level-issuing-and-receiving-stock/

1. Forms.py

Make a form in forms.py for issuing and receiving items

class IssueForm(forms.ModelForm):
class Meta:
model = Stock
fields = ['issue_quantity', 'issue_to']

class ReceiveForm(forms.ModelForm):
class Meta:
model = Stock
fields = ['receive_quantity', 'receive_by']
2. VIEWS.PY

import issueForm from forms.py

from .forms import IssueForm, ReceiveForm


Make a view to process issue and receive request

def issue_items(request, pk):


queryset = Stock.objects.get(id=pk)
form = IssueForm(request.POST or None, instance=queryset)
if form.is_valid():
instance = form.save(commit=False)
instance.quantity -= instance.issue_quantity
instance.issue_by = str(request.user)
messages.success(request, "Issued SUCCESSFULLY. " +
str(instance.quantity) + " " + str(instance.item_name) + "s now left in Store")
instance.save()

return redirect('/stock_detail/'+str(instance.id))
# return HttpResponseRedirect(instance.get_absolute_url())

context = {
"title": 'Issue ' + str(queryset.item_name),
"queryset": queryset,
"form": form,
"username": 'Issue By: ' + str(request.user),
}
return render(request, "add_items.html", context)

def receive_items(request, pk):


queryset = Stock.objects.get(id=pk)
form = ReceiveForm(request.POST or None, instance=queryset)
if form.is_valid():
instance = form.save(commit=False)
instance.quantity += instance.receive_quantity
instance.save()
messages.success(request, "Received SUCCESSFULLY. " +
str(instance.quantity) + " " + str(instance.item_name)+"s now in Store")

return redirect('/stock_detail/'+str(instance.id))
# return HttpResponseRedirect(instance.get_absolute_url())
context = {
"title": 'Reaceive ' + str(queryset.item_name),
"instance": queryset,
"form": form,
"username": 'Receive By: ' + str(request.user),
}
return render(request, "add_items.html", context)

3. Make urls for issue and receive

path('issue_items/<str:pk>/', views.issue_items, name="issue_items"),


path('receive_items/<str:pk>/', views.receive_items, name="receive_items"),
4. Add clickable anchor urls to the template

<a href="{% url 'issue_items' queryset.id %}"><div class='btn btn-danger'>ISSUE


THIS ITEM</div></a>
<a href="{% url 'receive_items' queryset.id %}"><div class='btn btn-
primary'>RECEIVE THIS ITEM</div></a>

27-how-to-configure-django-to-use-a-mysql-database/

MySQL server is one of the most stable relational database system. It has been
arround for long time and running behind a lot of website and applications. In this
tutorial, i will work you how to setup django to use MySQL server as the data store
for the application.

While we will be using MySQL on this tutorial, these steps should be similar to
other relational database systems like PostgreSQL.

We will be installing MySQL workbench but it is not required to run Django. MySQL
Workbench is only used to manage the database server by providing an easy Graphical
User Interface (GUI).

STEP 1: INSTALLING MYSQL SERVER, WORKBENCH AND SOME PREREQUISITES


Install MYSQL database, MYSQL workbench, and some prerequisites to connect Django
to the database.
sudo apt install mysql-server libmysqlclient-dev python-dev mysql-workbench
or use below command if you run an older version of ubuntu
sudo apt-get install mysql-server libmysqlclient-dev python-dev mysql-workbench
Enter the root password and confirm it when prompted

STEP 2: ACTIVATING VIRTUALENV AND INSTALLING MYSQLCLIENT


Navigate into the virtual environment, Activate the virtual environment and install
mysqlclient and occasionally mysql-python
cd venv(where venv is the name of the virtual environment)
source bin/activate
pip install mysqlclient

STEP 3: CREATING A DATABASE AND USERNAME


Open mysql workbench, create a database (schema) and username to be used to connect
to the database.

I will use these parameters:


database name = stockmgmt
Username = myusername
Password = myPassword

STEP 4: CONFIGURING DJANGO TO USE THE DATABASE CREATING IN STEP 3


In the application settings.py file, configure Django to use MYSQL Database instead
of the SQLite file (the default).
in this example we are using the database, username, and password created in the
above step:

database name = stockmgmt


Username = myusername
Password = myPassword

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'stockmgmt',
'USER': 'myusername',
'PASSWORD': 'myPassword',
}
}
STEP 5: CREATING TABLES IN THE NEWLY CREATED DATABASE
Django allows us to easily create tables in the database with a simple script
(python manage.py migrate)

Do migrate for Django to create the application tables to the newly configured
database.

You might want to delete all the files in the migration folder except __init__.py
if you want to are do a clean setup. Watch the video for more explanation.
./manage.py migrate
./manage.py runserver

28-how-to-setup-stock-reorder-level-alert/

1. Make a form for updating the reorder level

class ReorderLevelForm(forms.ModelForm):
class Meta:
model = Stock
fields = ['reorder_level']
2. Make a view for reorder level

def reorder_level(request, pk):


queryset = Stock.objects.get(id=pk)
form = ReorderLevelForm(request.POST or None, instance=queryset)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "Reorder level for " +
str(instance.item_name) + " is updated to " + str(instance.reorder_level))

return redirect("/list_items")
context = {
"instance": queryset,
"form": form,
}
return render(request, "add_items.html", context)
3. Make a url for editing the reorder level

path('reorder_level/<str:pk>/', views.reorder_level, name="reorder_level"),


4. Make a template tag condition with a div rapping the quantity field that will
apply a style to the field when the reorder level is equal to or less than the
quantity

<td>
{% if instance.quantity <= instance.reorder_level %}
<div style="background-color: orange;">{{instance.quantity}}</div>
{% else %}{{instance.quantity}}
{% endif %}
</td>
5. Add a column for reorder level and make is clickable to update the reorder level

<td><a href="{% url 'reorder_level' instance.id


%}">{{instance.reorder_level}}</a></td>

/29-how-to-authenticate-users-in-django-using-registration-redux/

1. Install django-registration-redux

pip install django-registration-redux


2. Add registration in to your INSTALLED_APPS

INSTALLED_APPS = [
....
'registration', #should be immediately above 'django.contrib.auth'
....
]
3. Migrate for registration tables to be created in the database

./manage.py migrate
4. Add the following lines to your settings.py file

ACCOUNT_ACTIVATION_DAYS = 7 # One-week activation window


REGISTRATION_AUTO_LOGIN = True # Automatically log the user in.
SITE_ID = 1
LOGIN_REDIRECT_URL = '/'
5. Add a url to include urls from registration app you just installed

from django.urls import include


path('accounts/', include('registration.backends.default.urls')),
6. In your template folder, make a copy of the home page and name it base.html,
paste in the following codes where you want the login field to appear.

{% block title %}
{% endblock %}

{% block content %}
{% endblock %}
7. Login to the app through this url: localhost:8000/accounts/login
logout URL is: localhost:8000/accounts/logout

8. Add a login / logout button on the navbar

<ul class="navbar-nav">
{% if request.user.is_authenticated %}
<li><a href="/accounts/logout"><button class="btn btn-danger">{{ user }} |
Logout</button></a></li>
{% else %}
<li><a href="/accounts/login">Login</a></li>
{% endif %}
</ul>
9. Import login required decorator and place them above all views that needs login
before accessing

from django.contrib.auth.decorators import login_required


@login_required
10. Hide navbar links from unauthenticated users

{% if request.user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="/list_items">List Items</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/add_items">Add Items</a>
</li>
{% endif %}

30-how-to-keep-the-previous-version-of-data-or-the-model-object-in-django/

In this section of the tutorial, we are going to keep the previous version of our
data and use it as our stock update history.

We can archive this by copying the content of the updated data into another table
called StockHistory.

1. Create another table similar to the Stock table. We will use Django models to
create it as follows:

class StockHistory(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True,
null=True)
item_name = models.CharField(max_length=50, blank=True, null=True)
quantity = models.IntegerField(default='0', blank=True, null=True)
receive_quantity = models.IntegerField(default='0', blank=True, null=True)
receive_by = models.CharField(max_length=50, blank=True, null=True)
issue_quantity = models.IntegerField(default='0', blank=True, null=True)
issue_by = models.CharField(max_length=50, blank=True, null=True)
issue_to = models.CharField(max_length=50, blank=True, null=True)
phone_number = models.CharField(max_length=50, blank=True, null=True)
created_by = models.CharField(max_length=50, blank=True, null=True)
reorder_level = models.IntegerField(default='0', blank=True, null=True)
last_updated = models.DateTimeField(auto_now_add=False, auto_now=False,
null=True)
timestamp = models.DateTimeField(auto_now_add=False, auto_now=False,
null=True)

Note that we are setting all the fields to accept blank data blank=True, null=True
and the date fields to auto_now_add=False, auto_now=False

This will give us the flexibility to pass data into it or leave it blank.

2. Do makemigration and migrate for the table called StockAudit to be created.


./manage.py makemigration
./manage.py migrate

3. Open MySQL workbench or any other database client, update the properties of the
StockHistory table and remove all checkboxes on all fields.
4. Create a trigger in MySQL-Server that will copy the content of the Stock table
to the StockHistory table when adding the data for the first time and when updating
the data.

The following script creates the trigger

DELIMITER //
DROP TRIGGER IF EXISTS after_stockmgmt_stock_update//
CREATE TRIGGER after_stockmgmt_stock_update AFTER UPDATE ON stockmgmgt_stock FOR
EACH ROW
BEGIN
IF new.issue_quantity = 0
THEN INSERT INTO stockmgmgt_stockhistory(
id,
last_updated,
category_id,
item_name,
quantity,
receive_quantity,
receive_by)
VALUES(
new.id,
new.last_updated,
new.category_id,
new.item_name,
new.quantity,
new.receive_quantity,
new.receive_by);

ELSEIF new.receive_quantity = 0
THEN INSERT INTO stockmgmgt_stockhistory(
id,
last_updated,
category_id,
item_name,
issue_quantity,
issue_to,
issue_by,
quantity)
VALUES(
new.id,
new.last_updated,
new.category_id,
new.item_name,
new.issue_quantity,
new.issue_to,
new.issue_by,
new.quantity);
END IF;
END//
DELIMITER ;
Note that in the script above, we have a condition is True on when issue_quantity
and receive_quantity =0

For this to work, in issue_items view, you will need to insert this line
instance.receive_quantity = 0
right after:
instance = form.save(commit=False)

and in receive_items view, insert this line


instance.issue_quantity = 0
right after:
instance = form.save(commit=False)

5: Make a view to list the content of the StockHistory table. Note that the
queryset is defined to pull data from the StockHistory model and not Stock model.
Don’t forget to import the StockHistory model.

@login_required
def list_history(request):
header = 'LIST OF ITEMS'
queryset = StockHistory.objects.all()
context = {
"header": header,
"queryset": queryset,
}
return render(request, "list_history.html",context)

6. Create a template for history data and name it list_history.html

<div class="display_table">
<table class='table'>
<thead>
<tr>
<th>COUNT</th>
<th>ID</th>
<th>CATEGORY</th>
<th>ITEM NAME</th>
<th>QUANTITY IN STORE</th>
<th>ISSUE QUANTITY</th>
<th>RECEIVE QUANTITY</th>
<th>LAST UPDATED</th>
</tr>
</thead>
{% for instance in queryset %}
<tr>

<td>{{forloop.counter}}</td>
<td>{{instance.id}}</td>
<td>{{instance.category}}</td>
<td><{{instance.item_name}}</td>
<td>{{instance.quantity}}</td>
<td>{{instance.issue_quantity}}</td>
<td>{{instance.receive_quantity}}</td>
<td>{{instance.last_updated}}</td>
</tr>
{% endfor %}
</table>
</div>

7: Make a URL for stockhistory list, and add the link in navbar.html
Add a URL in urls.py:

path('list_history/', views.list_history, name='list_history'),


8. Now add stock history link in navbar.html

<li class="nav-item">
<a class="nav-link" href="/list_history">List History</a>
</li>

31-how-to-filter-stock-history-and-export-to-csv-stock-management-system/

1. Make a form in forms.py. Name the form StockSearchForm. This form will be used
for filtering the stockHistory objects. We are going to filter based on ctategory
and item_name. Therefore, we will make a form with two fields, category and
item_name as seen below.

NOTE: If you are following the tutorial from the beginning, you must have this form
already

class StockSearchForm(forms.ModelForm):
export_to_CSV = forms.BooleanField(required=False)
class Meta:
model = Stock
fields = ['category', 'item_name']
2. Make a condition in the list_history view to apply the filter when the search
button is selected.

form = StockSearchForm(request.POST or None)


if request.method == 'POST':
category = form['category'].value()
queryset = StockHistory.objects.filter(

item_name__icontains=form['item_name'].value()
)

if (category != ''):
queryset = queryset.filter(category_id=category)

context = {
"form": form,
"header": header,
"queryset": queryset,
}
3. Make a form inputs in list_history.html template

<form method='POST' action=''>{% csrf_token %}


{{form|crispy}}
<input type="submit" value='Search'/>
</form>
4. To export the content to CSV, use this condition.

if form['export_to_CSV'].value() == True:
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="Stock
History.csv"'
writer = csv.writer(response)
writer.writerow(
['CATEGORY',
'ITEM NAME',
'QUANTITY',
'ISSUE QUANTITY',
'RECEIVE QUANTITY',
'RECEIVE BY',
'ISSUE BY',
'LAST UPDATED'])
instance = queryset
for stock in instance:
writer.writerow(
[stock.category,
stock.item_name,
stock.quantity,
stock.issue_quantity,
stock.receive_quantity,
stock.receive_by,
stock.issue_by,
stock.last_updated])
return response

32-rearranging-buttons-and-styling-pages/

In this blog, we want to rearrange the menus of our application. Removing them from
the nav-bar to the item-list page and then style the button.

1. Styling the list_items page

We will use bootstrap rows and columns to archive this. Create a row with two
columns. The bootstrap row has a size of 12 columns. We will use 2 column size for
the form section of the page. The table section will take the remaining 10 columns.

To create a row, use this code:

<div class="row"><!--Start of row-->

<div class="col-sm-2"><!--Start of first col-->


<form method='POST' action=''>{% csrf_token %}
{{form|crispy}}
<input class="btn btn-primary mybutton" type="submit" value='Search'/>
</form><br><br>
<br>
<a href="/add_items"><div class="btn btn-primary mybutton">Add
Items</div></a><br><br>
<a href="/list_history"><div class="btn btn-primary mybutton">List
History</div></a><br>
<br>
</div><!--End of first col-->

<div class="col-sm-10"><!--Start of second col-->


<table>
</table>
</div><!--End of second col-->

</div><!--End of row-->
2. We have used a class named mybutton on the links to the add_items and
list_history

mybutton is styled with the following css to give it a full with of the row that it
is in

.mybutton{
width: 100%;
}
That will change the design of list_items page from this:

To this:

3. Styling the add items page

<div class="row"><!--Start of row-->


<div class="col-sm-5"><!--Start of col-->
<div class="display_table">
<form method='POST' action=''>{% csrf_token %}
{{form|crispy}}
<input class="btn btn-primary" type="submit" value='Save'/>
</form>
</div>
</div><!--End of col-->
</div><!--End of row-->
That will change the design of add_items page from this:

To This:

4. Redirecting home button to list_items page

def home(request):
title = 'Welcome: This is the Home Page'
form = 'Welcome: This is the Home Page'
context = {
"title": title,
"test": form,
}
return redirect('/list_items')
5. Finally, remove the links from the nav-bar

33-how-to-do-a-date-range-filter-in-django-stock-management-system/

33 – HOW TO DO A DATE RANGE FILTER IN DJANGO – STOCK MANAGEMENT SYSTEM


Searching object in django can be archieved in multiple ways. In this video we will
try to search objects within a certain date range.

For example, we have an object that was issued out on different dates. Let’s say
one was

1 July 2020, 2nd July 2020, 5th July 2020, and 20th July 2020.

Now we want to filter all the issued items from 1st July 2020 up to today 28th July
2020.
This type of filter is what we want to archieve in this tutorial.

Feel free to leave a comment if you have any issue or needed some clarification
while implimenting this cool little feature.

STEP 1. MAKE A FORM IN FORMS.PY


Import StockHistory Model then create a form with the fields needed to do a search.
In this case, we will update the form we already used our previous blogs of this
series, and include two extra fields: start_date and end_date.

class StockHistorySearchForm(forms.ModelForm):
export_to_CSV = forms.BooleanField(required=False)
start_date = forms.DateTimeField(required=False)
end_date = forms.DateTimeField(required=False)
class Meta:
model = StockHistory
fields = ['category', 'item_name', 'start_date', 'end_date']
STEP 2. CREATE THE FILTER IN VIEWS.PY
Now that we have a form with the a start and end date field, we can use this fields
to do a range filter in the StockHistory Model.

In views.py, import and use the form created above in list_history view and then
add a filter criterion that looks for the date within the start and end date in the
form above.

queryset = StockHistory.objects.filter(
item_name__icontains=form['item_name'].value(),
last_updated__range=[
form['start_date'].value(),
form['end_date'].value()
]
)

NOTE: With this example (using date range), when selecting the start and end date,
the end date should be one day beyond the last date you want to to display in the
output. For example, if you want to select a date from

1st July 2020 to 28th July 2020,

Set your start date as 1st July 2020 and set the end date to 29th July 2020

34-how-to-add-jquery-and-jquery-ui-datepicker-to-django-stock-management-system/

1. Download jquery from “https://jquery.com/download/“

2. Download jquery-ui from “https://jqueryui.com/“

3. Link all the js and css files in both jQuery and jQuery-ui to the templates
(html pages)

<link href="{% static 'js/jquery-ui-1.12.1/jquery-ui.min.css' %}" rel="stylesheet">


<link href="{% static 'js/jquery-ui-1.12.1/jquery-ui.structure.min.css' %}"
rel="stylesheet">
<link href="{% static 'js/jquery-ui-1.12.1/jquery-ui.theme.min.css' %}"
rel="stylesheet">

<script src="{% static 'js/jquery-3.4.0.min.js' %}"></script>


<script src="{% static 'js/jquery-ui-1.12.1/jquery-ui.js' %}"></script>
<script src="{% static 'js/myjs.js' %}"></script>

4. Create a custom.js file in static/js folder where you will specify all your js
codes. In this file, add the following codes:

$(document).ready(function(){

$(".datetimeinput").datepicker({changeYear: true,changeMonth: true, dateFormat:


'yy-mm-dd'});

});

35-setting-up-modal-background-image-stock-management-system/

In this video, we will show you how to add backgroud image to the application, fade
in effect and fake loader in your application. In the dome video, you will notice
the application fades in when loading pages.

There is also a version button which when clicked, opens a modal with system
information as the content of the modal page.

1. ADDING A BACKGROUD IMAGE

This is done in css.

i. Copy the background image is img folder inside located in static folder.

ii. Open stylesheet.css and paste in this code below then refresh your application
while holding the ctrl key on the keyboard

body {
background-image: url("../img/bg.jpg");
}
2. ADDING MODAL PAGE

We want the version to be shown on all pages of the application. Add the modal page
content to the navbar since it’s visible on all pages.

<a href="#"><div id="version-display" data-toggle="modal" data-


target="#myModal">SMIS Ver: 1.0</div></a>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">

<div class="modal-header">
<!-- <button type="button" class="close" data-
dismiss="modal">&times;</button> -->
<h4 class="modal-title">System Information</h4>
</div>
<div class="modal-body">
<div class="dev-info">
<p class=""><b>STOCK MANAGEMENT INFORMATION SYSTEMS</b></p>
<p>VERSION: 1.O</p><br>

<p class="modal-header">DEVELOPER:</p>
<p>Arbcoms</p>
<p>4444444</p>
<p><img src="/static/img/logo.png" alt="Developer Logo"></p>

</div>
</div>

<div class="modal-footer">
<button type="button" class="btn btn-default" data-
dismiss="modal">Close</button>
</div>

</div>
</div>
</div>
MODAL CSS

Apply this css to style the Modal and appy the animation when the button is clicked

/* Version Button */
#version-display{
background-color: #e61c66;
color: white;
box-shadow: 5px 12px 12px #2e6da4;
text-align: center;
display: inline;
font-weight: bolder;
padding: 15px;
position: fixed;
top: 40px;
left: -5px;
z-index: 3000;
border-top-right-radius: 20px;
border-bottom-right-radius: 20px;
}

/* Modal Header */
.modal-header {
padding: 2px 16px;
background-color: #e61c66;
color: white;
}

/* Modal Body */
.modal-body {padding: 2px 16px;}

/* Modal Footer */
.modal-footer {
padding: 2px 16px;
background-color: #e61c66;
color: white;
}

/* Modal Content */
.modal-content {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
width: 100%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);

.dev-info{
width: 50%;
text-align: center;
font-family: helvetica;
font-weight: bold;
display: inline;
}

.dev-info-logo{
width: 50px;
float: left;
}

36-how-to-add-pagination-plus-fancy-progress-bar-in-django/

As our data grow, our table contains more and more data to display. Keeping this on
one page can make the users to scroll and keep scrolling to find data. Will it not
be nice to add some cool little pages so that our data gets more organized.

To make the app even fancier, we will add some dummy page loader progress bar. We
will not check how much page content is loaded but this can still be used for that.
That will be for another tutorial.

Setting up pagination

1. Download pagination plugin from the following url then extract and move it to
your js folder.

https://www.jqueryscript.net/table/Client-side-HTML-Table-Pagination-Plugin-with-
jQuery-Paging.html

2. Add the paging.js file to your project

<script src="{% static 'js/pager/paging.js' %}"></script>


3. Now in myjs.js, add the paging script below. limit:15 sets how many lines of
data to display on one page.

$('.table').paging({limit:15});
Style the page buttons:

/*Table paination styling*/


.paging-nav {
text-align: right;
padding-top: 2px;
font-size: 20px;
padding-bottom: 10px;
}

.paging-nav a {
margin: auto 1px;
text-decoration: none;
display: inline-block;
padding: 1px 7px;
background: #3287a8;
color: white;
border-radius: 100px;
}

.paging-nav .selected-page {
font-weight: bold;
color: #dc3545;
}
/* End Table paination styling*/
Setting up Progress Bar

1. Download NProgress from the URL provided below, extract it and move it to js
folder in your project.

https://github.com/rstacruz/nprogress

2. Add both css and js file to your project.

CSS Files:

<link href="{% static 'js/nprogress/nprogress.css' %}" rel="stylesheet">


JS File:

<script src="{% static 'js/nprogress/nprogress.js' %}"></script>


3. Add the code below in myjs.js file(That is the javascript where we write our own
javascrip codes).

NProgress.start();
NProgress.done();
Make sure myjs.js is in all your templates or at least on all the pages where you
want to run pagination and NProgress

https://arbcoms.com/whats-next-apps-coming-up/
Hello everyone. In this video, we will discuss few apps that are coming up with a
short dome. We thing this will give you a good understanding of how to build apps
using django framework.

These ranges from simple apps to a more complex one:


Todo Apps
Task Management System
Point of Sales Application
Task Management System
Invoice Management system
Leave Management System
and many more.
We believe you will learn alot yet enjoy the tutorials.
We wanna take this opotunity to thanks all the viewers for the 1000 subscribers.
We really apprciate your subs.

Enjoy learning with us.

You might also like