Skill Deve
Skill Deve
COLLEGE OF ENGINEERING
KUKATPALLY, HYDERABAD – 500085
Certificate
This is to certify that of CSM II year I
Semester bearing the Hall-Ticket number has
fulfilled his SKILL DEVELOPMENT LAB record for the
academic year 2023-2024.
Date of Examination
1
J.N.T.U.H. UNIVERSITY COLLEGE OF ENGINEERING
HYDERABAD
(Autonomous)
KUKATPALLY, HYDERABAD – 500 085
List of Experiments
2
Django Installation
Django is a Python framework that makes it easier to create web sites using Python.
Django takes care of the difficult stuff so that you can concentrate on building your web
applications.
To check if your system has Python installed, run this command in the command prompt:
python --version
If Python is installed, you will get a result with the version number, like this
Python 3.9.2
If Python is not installed on the computer, then it should be downloaded from the following
website: https://www.python.org/
PIP
To install Django, you must use a package manager like PIP, which is included in Python
from version 3.4.
To check if your system has PIP installed, run this command in the command prompt:
pip --version
If PIP is installed, you will get a result with the version number.
If PIP is not installed, it should be downloaded and installed from this page:
https://pypi.org/project/pip/
Virtual Environment
It is suggested to have a dedicated virtual environment for each Django project, and one way
to manage a virtual environment is venv, which is included in Python.
3
Create a virtual environment of name myworld by running this command in the command
prompt.
Windows:
This will set up a virtual environment, and create a folder named "myworld" with subfolders
and files, like this:
myworld
Include
Lib
Scripts
pyvenv.cfg
Windows:
myworld\Scripts\activate.bat
Install Django
Note: Remember to install Django while you are in the virtual environment!
Windows:
Which will give a result that looks like this (at least on my Windows machine):
Collecting Django
Downloading Django-4.0.3-py3-none-any.whl (8.0 MB)
|████████████████████████████████| 8.0 MB 2.2 MB/s
Collecting sqlparse>=0.2.2
Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB)
Collecting asgiref<4,>=3.4.1
Downloading asgiref-3.5.0-py3-none-any.whl (22 kB)
Collecting tzdata; sys_platform == "win32"
Downloading tzdata-2021.5-py2.py3-none-any.whl (339 kB)
|████████████████████████████████| 339 kB 6.4 MB/s
Installing collected packages: sqlparse, asgiref, tzdata, Django
Successfully installed Django-4.0.3 asgiref-3.5.0 sqlparse-0.4.2 tzdata-2021.5
WARNING: You are using pip version 20.2.3; however, version 22.3 is available.
You should consider upgrading via the 'C:\Users\Name\myworld\Scripts\python.exe -m pip
install --upgrade pip' command.
4
Now, Django has been installed successfully.
5
Creating and running a project in Django
Aim: To create and run a Django project
Procedure:
Activate the virtual environment which is created and Django installed and navigate to the
desired folder to the project.
Now run the Django command to start a project with desired name.
tennis
manage.py
tennis/
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
Run the Django Project to see how it looks in the browser window.
Navigate to the /tennis folder and execute this command in the command prompt:
cd tennis
You have 18 unapplied migration(s). Your project may not work properly until you apply the
migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
October 27, 2022 - 13:03:14
Django version 4.1.2, using settings 'tennis.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
6
Open a new browser window and type 127.0.0.1:8000 in the address bar.
The result:
Press [CTRL] [BREAK], or [CTRL] [C] to stop the server and you should be back in the
virtual environment.
Result: Now, a Django project has been created and it run in a browser window.
7
Create App and Executing views
Aim: To create a Django app and Execute views.
Procedure:
tennis
manage.py
tennis/
members/
migrations/
__init__.py
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
Changing views
tennis/members/views.py:
def members(request):
return HttpResponse("Hello world!")
Create a file named urls.py in the app folder, and type this code in it:
tennis/members/urls.py:
8
from django.urls import path
from . import views
urlpatterns = [
path('members/', views.members, name='members'),
]
There is a file called urls.py on the tennis folder, open that file and add the include
module in the import statement, and also add a path() function in the urlpatterns[] list,
with arguments that will route users that comes in via 127.0.0.1:8000/.
tennis/tennis/urls.py:
urlpatterns = [
path('', include('members.urls')),
path('admin/', admin.site.urls),
]
Result: Now, a Django app has been created and view has been executed in a browser
window.
9
Using templates in Django
Aim: To use html templates in Django app
Procedure:
Create a templates folder inside the members folder, and create a HTML file named
first.html.
tennis
manage.py
tennis/
members/
templates/
first.html
tennis/members/templates/myfirst.html:
<!DOCTYPE html>
<html>
<body>
<h1>Hello World!</h1>
<p>Welcome to my first Django project!</p>
</body>
</html>
tennis/members/views.py:
def members(request):
return render(request,“first.html”,{})
10
Look up the INSTALLED_APPS[] list and add the members app like this:
tennis/tennis/settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'members'
]
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
(myworld) C:\Users\Name\myworld\tennis>
Start the server by navigating to the /tennis folder and execute this command:
11
Result: Templates have been used in Django app.
12
Redirecting from one page to another using Django
Aim: To redirect from one page to another in Django app
Procedure:
<!DOCTYPE html>
<html>
<head>
<title>Success </title>
</head>
<body>
Redirection Successful.
</body>
</html>
Now, open first.html file and replace the code with the following html:
<!DOCTYPE html>
<html>
<body>
</script>
</body>
</html>
tennis/members/views.py:
def members(request):
return render(request,“first.html”,{})
13
def success(request):
return render(request,”second.html”,{})
Then, open urls.py in app folder,
tennis/members/urls.py:
urlpatterns = [
path('members/', views.members, name='members'),
path('members/second', views.success, name='success'),
]
Now, run the server with the following command in command prompt:
python manage.py runserver
14
Result: Successfully we are able to redirect from one page to another.
15
Take user inputs and redirect using Django
Aim: To take inputs and redirect from one page to another in Django app
Procedure:
<!DOCTYPE html>
<html>
<head>
<title>Success </title>
</head>
<body>
<h1>Success!</h1>
</body>
</html>
Now, open first.html file and replace the code with the following html:
<!DOCTYPE html>
<html>
<body>
</script>
</body>
</html>
tennis/members/views.py:
16
def members(request):
return render(request,“first.html”,{})
def success(request):
return render(request,”second.html”,{})
Then, open urls.py in app folder,
tennis/members/urls.py:
urlpatterns = [
path('members/', views.members, name='members'),
path('members/second', views.success, name='success'),
]
Now, run the server with the following command in command prompt:
python manage.py runserver
17
Result: Successfully we are able to take inputs redirect from one page to another.
18
CRUD Operations in Django
Aim: To implement CRUD operations in Django
Procedure:
Open it, and add a Member table by creating a Member class, and describe the table fields in
it:
tennis/members/models.py:
class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
The first field, firstname, is a Text field, and will contain the first name of the members.
The second field, lastname, is also a Text field, with the member's last name.
Make Migrations
Navigate to the /tennis/ folder and run this command:
The output:
(myworld) C:\Users\Name\myworld\tennis>
tennis/members/migrations/0001_initial.py:
class Migration(migrations.Migration):
19
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Member',
fields=[
('id', models.BigAutoField(auto_created=True,
primary_key=True, serialize=False, verbose_name='ID')),
('firstname', models.CharField(max_length=255)),
('lastname', models.CharField(max_length=255)),
],
),
]
The output:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, members, sessions
Running migrations:
Applying members.0001_initial... OK
(myworld) C:\Users\Name\myworld\tennis>
BEGIN;
--
-- Create model Member
--
CREATE TABLE "members_member" ("id" integer NOT NULL PRIMARY KEY
AUTOINCREMENT, "firstname" varchar(255) NOT NULL, "lastname" varchar(255) NOT
NULL); COMMIT;
20
Procedure to Add Records
Open a python shell:
Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
Hitting [enter] and writing this to look at the empty Member table:
>>> Member.objects.all()
<QuerySet []>
>>> Member.objects.all().values()
21
>>> member3 = Member(firstname='Lene', lastname='Refsnes')
>>> member4 = Member(firstname='Stale', lastname='Refsnes')
>>> member5 = Member(firstname='Jane', lastname='Doe')
>>> members_list = [member1, member2, member3, member4, member5]
>>> for x in members_list:
>>> x.save()
>>> Member.objects.all().values()
<QuerySet [{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes'},
{'id': 2, 'firstname': 'Tobias', 'lastname': 'Refsnes'},
{'id': 3, 'firstname': 'Linus', 'lastname': 'Refsnes'},
{'id': 4, 'firstname': 'Lene', 'lastname': 'Refsnes'},
{'id': 5, 'firstname': 'Stale', 'lastname': 'Refsnes'},
{'id': 6, 'firstname': 'Jane', 'lastname': 'Doe'}]>
Update Records
now,
>>> x.firstname
'Stale'
>>> x.save()
Checking if the record got updated,
>>> Member.objects.all().values()
Delete Records
To delete a record in a table, start by getting the record you want to delete:
x will now represent the member at index 5, which is "Jane Doe", but to make sure, let us see
if that is correct:
>>> x.firstname
'Jane'
>>> x.delete()
If we look at the Member Model, we can see that 'Jane Doe' is removed from the Model:
>>> Member.objects.all().values()
<QuerySet [{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes'},
{'id': 2, 'firstname': 'Tobias', 'lastname': 'Refsnes'},
{'id': 3, 'firstname': 'Linus', 'lastname': 'Refsnes'},
{'id': 4, 'firstname': 'Lene', 'lastname': 'Refsnes'},
{'id': 5, 'firstname': 'Stalikken', 'lastname': 'Refsnes'}]>
23
Django Update Model
Add Fields in the Model
open the models.py file, and making the changes to add a new field:
tennis/members/models.py:
class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
phone = models.IntegerField()
joined_date = models.DateField()
Adding phone number and joined_date to the models and making the migrations by the
following command:
selecting option 2, and open the models.py file again and allow NULL values for the two
new fields:
tennis/members/models.py:
class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
phone = models.IntegerField(null=True)
joined_date = models.DateField(null=True)
24
- Add field joined_date to member
- Add field phone to member
Operations to perform:
Apply all migrations: admin, auth, contenttypes, members, sessions
Running migrations:
Applying members.0002_member_joined_date_member_phone... OK
Insert Data
First we enter the Python Shell:
Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
At the bottom, after the three >>> write the following (and hit [enter] for each line):
This will insert a phone number and a date in the Member Model, at least for the first record,
the four remaining records will for now be left empty.
>>> Member.objects.all().values()
25
<QuerySet [
{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes', 'phone': 5551234, 'joined_date': datetime.date(2022,
1, 5)},
{'id': 2, 'firstname': 'Tobias', 'lastname': 'Refsnes', 'phone': None, 'joined_date': None},
{'id': 3, 'firstname': 'Linus', 'lastname': 'Refsnes', 'phone': None, 'joined_date': None},
{'id': 4, 'firstname': 'Lene', 'lastname': 'Refsnes', 'phone': None, 'joined_date': None},
{'id': 5, 'firstname': 'Stalikken', 'lastname': 'Refsnes', 'phone': None, 'joined_date': None}]>
26
Form validation
Aim: To implement form validation in Django
Procedure:
Now, open second.html file and replace the code with the following html:
Write this code in the file.
<!DOCTYPE html>
<html>
<head>
<title>Success </title>
</head>
<body>
<div id="name"></div>
<script>
</script>
</body>
</html>
Now, open first.html file and replace the code with the following html:
<!DOCTYPE html>
27
<html><head><meta charset="utf-8"></head>
<title>Form</title><head></head><body>
<h1></h1>
<h1></h1>
<form action="{% url 'success'%}" method="post">
{% csrf_token %}
<label for name="name">enter yor name</label>
<input type="text" id="name" name="name" required>
<br>
<label for name="mail">enter yor email</label>
<input type="email" id="mail" name="mail" required>
<br>
<label for name="name">enter yor password</label>
<input type="password" id="pass" name="pass" required>
<br>
<button onclick="fun()"> Submit </button>
</form>
<script>
function fun(){
localStorage.setItem("name",document.getElementById("name").value);
localStorage.setItem("mail",document.getElementById("mail").value);
localStorage.setItem("pass",document.getElementById("pass").value);
}
</script>
</body></html>
tennis/members/views.py:
def members(request):
return render(request,“first.html”,{})
def success(request):
return render(request,”second.html”,{})
Now, run the server with the following command in command prompt:
python manage.py runserver
28
And, when button is clicked.
Result: Form input has been taken and validation is done in Django.
29
Creating a Dynamic Webpage
Aim: To implement dynamic webpage in Django
Procedure:
Now, open second.html file and replace the code with the following html:
Write this code in the file.
<!DOCTYPE html>
<html>
<head>
<title>Success </title>
</head>
<body>
<p id="name"></p>
<script>
document.getElementById("name").textContent=”Welcome,
“+localStorage.getItem("name");
</script>
</body>
</html>
Now, open first.html file and replace the code with the following html:
<!DOCTYPE html>
<html><head><meta charset="utf-8"></head>
<title>Form</title><head></head><body>
<h1></h1>
<form action="{% url 'success'%}" method="post">
{% csrf_token %}
<label for name="name">enter your name</label>
<input type="text" id="name" name="name" required>
<br>
<label for name="name">enter password</label>
<input type="password" id="pass" name="pass" required>
<br>
<button onclick="fun()"> Submit </button>
</form>
<script>
function fun(){
localStorage.setItem("name",document.getElementById("name").value);
}
</script>
</body></html>
tennis/members/views.py:
30
def members(request):
return render(request,“first.html”,{})
def success(request):
return render(request,”second.html”,{})
Now, run the server with the following command in command prompt:
python manage.py runserver
31
32