0% found this document useful (0 votes)
4 views32 pages

Skill Deve

The document provides a comprehensive guide on installing and using Django, a Python web framework, including setting up a virtual environment, creating and running a Django project, and implementing CRUD operations. It details the steps to create a Django app, manage views, use HTML templates, and handle user inputs with redirection. Additionally, it covers database model creation and migration processes necessary for managing data within a Django application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views32 pages

Skill Deve

The document provides a comprehensive guide on installing and using Django, a Python web framework, including setting up a virtual environment, creating and running a Django project, and implementing CRUD operations. It details the steps to create a Django app, manage views, use HTML templates, and handle user inputs with redirection. Additionally, it covers database model creation and migration processes necessary for managing data within a Django application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

J.N.T.U.H.

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.

Signature of the Head of the Department Signature of the


staff member

Date of Examination

Internal Examiner External Examiner

1
J.N.T.U.H. UNIVERSITY COLLEGE OF ENGINEERING
HYDERABAD
(Autonomous)
KUKATPALLY, HYDERABAD – 500 085

Name Roll Number

Class Year Laboratory

List of Experiments

S.No. Name of the Experiment Date of Page Remarks


Experiment Number

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.

Django emphasizes reusability of components, also referred to as DRY (Don't Repeat


Yourself), and comes with ready-to-use features like login system, database connection and
CRUD operations (Create Read Update Delete).

To install Django python should be install on the computer

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.

pip 20.2.3 from c:\python39\lib\site-packages\pip (python 3.9)

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:

python -m venv myworld

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

Then, activate the virtual environment by running this command:

Windows:

myworld\Scripts\activate.bat

Install Django
Note: Remember to install Django while you are in the virtual environment!

Django is installed using pip, with this command:

Windows:

(myworld) C:\Users\Name>python -m pip install Django

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:

Procedure to create virtual environment:

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.

django-admin startproject tennis

Django created a tennis folder on computer, with this content:

tennis
manage.py
tennis/
__init__.py
asgi.py
settings.py
urls.py
wsgi.py

Running the Django Project server

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

python manage.py runserver

Which will produce this result:

Watching for file changes with StatReloader


Performing system checks...

System check identified no issues (0 silenced).

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:

Procedure to create an app

Start by navigating to the project folder.

Then, create an app members with the command:

python manage.py startapp members

Django creates a folder named members in my project, with this content:

tennis
manage.py
tennis/
members/
migrations/
__init__.py
__init__.py
admin.py
apps.py
models.py
tests.py
views.py

Changing views

Open the views.py file using VSCode or notepad.

Replace the content with this:

tennis/members/views.py:

from django.shortcuts import render


from django.http import HttpResponse

def members(request):
return HttpResponse("Hello world!")

Now, Adding URLs

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:

from django.contrib import admin


from django.urls import include, path

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

Navigate to the tennis folder and run this command:

python manage.py runserver

In the browser window, type 127.0.0.1:8000/members/ in the address bar.

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.

The file structure should be like this:

tennis
manage.py
tennis/
members/
templates/
first.html

Open the HTML file and insert the following:

tennis/members/templates/myfirst.html:

<!DOCTYPE html>
<html>
<body>

<h1>Hello World!</h1>
<p>Welcome to my first Django project!</p>

</body>
</html>

Modifying the View


Open the views.py file and replace the members view with this:

tennis/members/views.py:

from django.shortcuts import render

def members(request):
return render(request,“first.html”,{})

Procedure to change Settings


To be able to work with more complicated stuff than "Hello World!", We have to tell Django
that a new app is created.

This is done in the settings.py file in the tennis folder.

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'
]

Then run this command:

python manage.py migrate

Which will produce this output:

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:

python manage.py runserver

In the browser window, type 127.0.0.1:8000/members/ in the address bar.

The result should look like this:

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:

Create a new html file named second.html in the templates folder.


Write this code in the file.

<!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>

<h1>Django url redirection</h1>


<p>Click the button to redirect </p>
<button onclick=”fun()”> Redirect </button>
<script>
function fun(){
window.location.href=”{% url ‘success’%}”;
}

</script>
</body>
</html>

Open views.py file and add a code to make it final as,

tennis/members/views.py:

from django.shortcuts import render

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:

from django.urls import path


from . import views

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

In the browser window, type 127.0.0.1:8000/members/ in the address bar.

The view should be this.

And, when button is clicked.

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:

Create a new html file named second.html in the templates folder.


Write this code in the file.

<!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>

<p>Enter your details<p>


Enter your name:<input type=”text”>
<br>
Enter password:<input type=”password”>
<br>
<button onclick=”fun()”>Submit</button>
<script>
function fun(){
window.location.href=”{% url ‘success’%}”;
}

</script>
</body>
</html>

Open views.py file and add a code to make it final as,

tennis/members/views.py:

from django.shortcuts import render

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:

from django.urls import path


from . import views

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

In the browser window, type 127.0.0.1:8000/members/ in the address bar.

The view should be this.

And, when button is clicked.

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:

Procedure to Create Table (Model)


To create a model, navigate to the models.py file in the /members/ folder.

Open it, and add a Member table by creating a Member class, and describe the table fields in
it:

tennis/members/models.py:

from django.db import models

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.

Both firstname and lastname is set up to have a maximum of 255 characters.

Make Migrations
Navigate to the /tennis/ folder and run this command:

python manage.py makemigrations members

The output:

Migrations for 'members':


members\migrations\0001_initial.py
- Create model Member

(myworld) C:\Users\Name\myworld\tennis>

The file created is,

tennis/members/migrations/0001_initial.py:

# Generated by Django 5.0.1 on 2024-01-08 11:14

from django.db import migrations, models

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)),
],
),
]

Run the migrate command:

python manage.py migrate

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>

Procedure to view SQL


To view the sql , the command should be run;

python manage.py sqlmigrate members 0001

Which will result in this output:

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 manage.py shell

The result should be something like this:

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 >>>

>>> from members.models import Member

Hitting [enter] and writing this to look at the empty Member table:

>>> Member.objects.all()

This gives an empty QuerySet object, like this:

<QuerySet []>

A QuerySet is a collection of data from a database.

Adding a record to the table, by executing these two lines:

>>> member = Member(firstname='Emil', lastname='Refsnes')


>>> member.save()

Executing this command to see if the Member table got a member:

>>> Member.objects.all().values()

The result is this:

<QuerySet [{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes'}]>

Add Multiple Records


Adding multiple records by making a list of Member objects, and execute .save() on each
entry:

>>> member1 = Member(firstname='Tobias', lastname='Refsnes')


>>> member2 = Member(firstname='Linus', lastname='Refsnes')

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()

Now there are 6 members in the Member table:

>>> 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

>>> from members.models import Member


>>> x = Member.objects.all()[4]

x will now represent the member at index 4, which is "Stale Refsnes"

now,

>>> x.firstname

This should give you this result:

'Stale'

Changing the values of this record:

>>> x.firstname = "Stalikken"

>>> x.save()
Checking if the record got updated,

>>> Member.objects.all().values()

The result is:

<QuerySet [{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes'},


{'id': 2, 'firstname': 'Tobias', 'lastname': 'Refsnes'},
22
{'id': 3, 'firstname': 'Linus', 'lastname': 'Refsnes'},
{'id': 4, 'firstname': 'Lene', 'lastname': 'Refsnes'},
{'id': 5, 'firstname': 'Stalikken', 'lastname': 'Refsnes'},
{'id': 6, 'firstname': 'Jane', 'lastname': 'Doe'}]>

Delete Records
To delete a record in a table, start by getting the record you want to delete:

>>> from members.models import Member


>>> x = Member.objects.all()[5]

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

This gives this result:

'Jane'

Now deleting the record:

>>> x.delete()

The result will be:

(1, {'members.Member': 1})

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:

from django.db import models

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:

python manage.py makemigrations members

python manage.py makemigrations members

the database needs something to populate existing rows.


Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:

selecting option 2, and open the models.py file again and allow NULL values for the two
new fields:

tennis/members/models.py:

from django.db import models

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)

And make the migration once again:

python manage.py makemigrations members

Which will result in this:

Migrations for 'members':


members\migrations\0002_member_joined_date_member_phone.py

24
- Add field joined_date to member
- Add field phone to member

Run the migrate command:

python manage.py migrate

Which will result in this output:

Operations to perform:
Apply all migrations: admin, auth, contenttypes, members, sessions
Running migrations:
Applying members.0002_member_joined_date_member_phone... OK

(myworld) C:\Users\Your Name\myworld\tennis>

Insert Data
First we enter the Python Shell:

python manage.py shell

Now in the shell, the result should be something like this:

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):

>>> from members.models import Member


>>> x = Member.objects.all()[0]
>>> x.phone = 5551234
>>> x.joined_date = '2022-01-05'
>>> x.save()

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.

Execute this command to see if the Member table got updated:

>>> Member.objects.all().values()

The result should look like this:

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}]>

Result: Successfully we are able to implement CRUD operation in Django.

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>

// Get the input elements


var name = localStorage.getItem("name");
var password = localStorage.getItem("pass");
var email = localStorage.getItem("mail");

// Define the regular expressions for name and email validation


var regName = /^[A-Za-z]+$/; // Name should only contain letters
var regEmail = /^\w+([\.-]?\w+)@\w+([\.-]?\w+)(\.\w{2,3})+$/; // Email
should have a valid format

// Check if the name is valid


if (!regName.test(name)) {
alert("Name must only contain letters");
document.getElementById("name").textContent = "Name must only contain
letters";
}
else if (!regEmail.test(email)) {
alert("Email must have a valid format");
document.getElementById("name").textContent = "Name must only contain
letters";
}else {
document.getElementById("name").textContent = "Welcome, "+name;
}

// If everything is valid, return true

</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>

Open views.py file and add a code to make it final as,

tennis/members/views.py:

from django.shortcuts import render

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

In the browser window, type 127.0.0.1:8000/members/ in the address bar.

The view should be this.

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>

Open views.py file and add a code to make it final as,

tennis/members/views.py:

from django.shortcuts import render

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

In the browser window, type 127.0.0.1:8000/members/ in the address bar.

The view should be this.

And, when button is clicked.

Result: Dynamic webpage has been implemented in Django successfully.

31
32

You might also like