0% found this document useful (0 votes)
3 views

Django Manika Final (2)

This practical file on Django, submitted by Manika Kumari, outlines various tasks related to Django development, including installation, project creation, app development, and CRUD operations. It serves as a comprehensive guide for students to learn and implement Django features through hands-on exercises. The document is structured with an index and detailed steps for each task, making it a useful resource for understanding Django framework functionalities.

Uploaded by

0rockykarak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Django Manika Final (2)

This practical file on Django, submitted by Manika Kumari, outlines various tasks related to Django development, including installation, project creation, app development, and CRUD operations. It serves as a comprehensive guide for students to learn and implement Django features through hands-on exercises. The document is structured with an index and detailed steps for each task, making it a useful resource for understanding Django framework functionalities.

Uploaded by

0rockykarak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

PRACTICAL FILE

ON
DJANGO
Submitted by:
Manika kumari
Enrollment No.: 01196702022
Batch: 2022-2025

Under the guidance of


Mrs. Priyanka

Kamal Institute of Higher Education and Advance


Technology
Affiliated to Guru Gobind Singh Indraprastha University

K-1 Extension,
Mohan Garden
New Delhi
11005

1
INDEX
S. No. TITLE Page
No.
Q1 Install Python including installation of pip,installation 4-5

and setting up virtual environment, installation of


Django
Q2 Create a new django project using command line 6

Q3 create a “Hello World” App in Django. 7-8

Q4 create a Django Form using forms.py 9-11

Q5 Create a Django app Using Django Templates features i.e. 12-15


Creating Template Objects , Rendering a Template ,
Multiple Contexts, Context Variable Lookup, Playing with
Context Objects, Template Loading, include Template Tag.
Q6 App to connect templates with models to serve data 16-18
dynamically
Q7 Creating and using CRUD class based view 19-22
Q8 Rendering a model in Django Admin Interfac 23-24

Q9 Create a Dynamic Feedback form with validations 25-27

Q10 write a Django web app to use parameters in Views.py 28

Q11 write a Django web app using control statements (If, for 29-31
etc.)
Q12 using blocks in Django Template and Extend base.html in 32-34
Templates
Q13 Work with Django humanize 35-37
(https://docs.djangoproject.com/en/3.2/ref/contrib/huma
nize/)
Q14 Work with Django Template built in Tags and Filter 38-40
(https://docs.djangoproject.com/en/3.2/ref/templates/bui
ltins/)

2
Q15 Handling 404, 502 pages in Django 41-45

3
Q.1 Install Python including installation of pip,installation
and setting up virtual environment, installation of Django.
Steps:
1. Install Python
here are the basic steps to install Python:
1. Go to the official Python website (python.org) and navigate to the
Downloads section.
2. Choose the version of Python you want to install (usually the latest stable
release, like Python 3.9).
3. Select the appropriate installer for your operating system (Windows, macOS,
or Linux).
4. Download the installer and run it.
5. Follow the installation wizard instructions, making sure to check the box that
adds Python to your system PATH (this makes it easier to run Python from the
command line).
2. Check python installation

3. Install pip
Pip comes bundled with python version 3.4 and above by default. To check if
pip is installed ,we can type

4. install virtualenv

5. create virtual environment

4
6. Activate the virtual environment

7. Install Django

8. verify your installation

5
Q. 2 Create a new django project using command line
Steps:
To create a new Django project using the command line, follow these steps:
1. **Navigate to the directory where we want to create your Django
project:**
2. **Activate your virtual environment (if you created one):**
If you're using a virtual environment, activate it using the appropriate
command:

3. **Create the Django project:**

4. **Navigate into the project directory:**

5. **Verify the project structure:**


myproject/
├── manage.py
└── myproject/
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py

6
Q. 3 create a “Hello World” App in Django.
Code:

1. create a new Django app

2. Define a view
Views.py

3. Create a URL mapping

4. Include apps url in project’s url

7
Output:

8
Q. 4 create a Django Form using forms.py
Code:
Create model for it
Models.py

Forms.py

9
Views.py
from django.shortcuts import render, redirect
from .forms import ContactForm
from .models import ContactMessage

def contact_us(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Save form data to the database
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
ContactMessage.objects.create(name=name, email=email,
message=message)
return redirect('contact_success') # Redirect to a success page
else:
form = ContactForm()
return render(request, 'contact/contact_us.html', {'form': form})

10
urls.py
from django.urls import path
from contact.views import contact_us, contact_success

urlpatterns = [
path('contact/', contact_us, name='contact_us'),
path('contact/success/', contact_success, name='contact_success'),
]

Output:

11
Q.5 Create a Django app Using Django Templates features
i.e. Creating Template Objects , Rendering a Template ,
Multiple Contexts, Context Variable Lookup, Playing with
Context Objects, Template Loading, include Template Tag,
Code:
1. **Create a Django app:**

2. **Define a view:**
from django.shortcuts import render

def home(request):
context = {
'title': 'Welcome to My Website!',
'content': 'This is a sample content for the homepage.',
'author': ‘monika’
}
return render(request, 'myapp/home.html', context)

12
3. **Create a template:**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h1>{{ title }}</h1>
<p>{{ content }}</p>
<p>Author: {{ author }}</p>
</body>
</html>

4. **Define URL mapping:**


Define a URL mapping in our app's `urls.py` file (`myapp/urls.py`):

from django.urls import path


from .views import home

urlpatterns = [
path('', home, name='home'),
]

13
5. **Load the template in the main template:**
Now, let's create a main template (`base.html`) that includes the `home.html`
template. Create a file named `base.html` inside the `templates` directory (not
inside `myapp`):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>

6. **Update `home.html` to extend `base.html`:**


{% extends 'base.html' %}

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

{% block content %}
<h1>{{ title }}</h1>
<p>{{ content }}</p>
<p>Author: {{ author }}</p>
{% endblock %}

14
7. **Run the server:**
python manage.py runserver

OUTPUT

15
Q.6 App to connect templates with models to serve data
dynamically
Code:
To create a Django app that connects templates with models to serve data
dynamically, we'll need to follow these steps:
1. **Define Models:**
from django.db import models

class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
author = models.CharField(max_length=50)
created_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.title

2. **Run Migrations:**
python manage.py makemigrations
python manage.py migrate

16
3. **Create Views:**
from django.shortcuts import render
from .models import Post
def post_list(request):
posts = Post.objects.all()
return render(request, 'myapp/post_list.html', {'posts': posts})

4. **Create Templates:**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Post List</title>
</head>
<body>
<h1>Blog Posts</h1>
<ul>
{% for post in posts %}
<li>
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<p>Author: {{ post.author }}</p>
<p>Created at: {{ post.created_at }}</p>
</li>
{% endfor %}
</ul>

17
</body>
</html>

5. **Define URLs:**
from django.urls import path
from .views import post_list
urlpatterns = [
path('posts/', post_list, name='post_list'),
]

OUTPUT:

18
Q. 7 Creating and using CRUD class based view
Code:
1. **Define Models:**
# models.py
from django.db import models

class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
author = models.CharField(max_length=50)
created_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.title

2. **Import Necessary Modules:**


# views.py
from django.views.generic import ListView, DetailView, CreateView,
UpdateView, DeleteView
from django.urls import reverse_lazy
from .models import Post

19
3. **Create Class-Based Views:**
# views.py
class PostListView(ListView):
model = Post
template_name = 'post_list.html'

class PostDetailView(DetailView):
model = Post
template_name = 'post_detail.html'

class PostCreateView(CreateView):
model = Post
template_name = 'post_form.html'
fields = ['title', 'content', 'author']

class PostUpdateView(UpdateView):
model = Post
template_name = 'post_form.html'
fields = ['title', 'content', 'author']

class PostDeleteView(DeleteView):
model = Post
template_name = 'post_confirm_delete.html'
success_url = reverse_lazy('post_list')

20
4. **Define URLs:**
# urls.py
from django.urls import path
from .views import PostListView, PostDetailView, PostCreateView,
PostUpdateView, PostDeleteView

urlpatterns = [
path('', PostListView.as_view(), name='post_list'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post_detail'),
path('post/new/', PostCreateView.as_view(), name='post_create'),
path('post/<int:pk>/edit/', PostUpdateView.as_view(),
name='post_update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(),
name='post_delete'),
]

OUTPUT:

21
22
Q. 8 Rendering a model in Django Admin Interface.
Code:
1. **Register Model with Admin Interface:**
# admin.py
from django.contrib import admin
from .models import Post

admin.site.register(Post)

2. **Customize Admin Interface (Optional):**


# admin.py
from django.contrib import admin
from .models import Post

class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'created_at']
list_filter = ['author', 'created_at']
search_fields = ['title', 'content']

admin.site.register(Post, PostAdmin)

3. **Run the Development Server:**


python manage.py runserver

23
4. **Access the Admin Interface:**
Open our browser and navigate to `http://127.0.0.1:8000/admin/`. Log in
with a superuser account (we can create one using `python manage.py
createsuperuser` if we haven't already).we should see our model listed in the
admin interface.

OUTPUT:

24
Q.9 Create a Dynamic Feedback form with validations
Code:
1. **Define Form Class with Validation:**
# forms.py
from django import forms
class FeedbackForm(forms.Form):
name = forms.CharField(max_length=100, label='Your Name')
email = forms.EmailField(label='Your Email')
feedback = forms.CharField(widget=forms.Textarea, label='Your Feedback')
2. **Create Template for the Form:**
<!-- feedback_form.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Feedback Form</title>
</head>
<body>
<h1>Feedback Form</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit Feedback</button>
</form>
</body>
</html>

25
3. **Implement View for the Form:**
# views.py
from django.shortcuts import render
from .forms import FeedbackForm

def feedback_form(request):
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
# Process valid form data (e.g., save to database)
return render(request, 'success.html')
else:
form = FeedbackForm()
return render(request, 'feedback_form.html', {'form': form})

4. **Define URL Mapping:**


# urls.py
from django.urls import path
from .views import feedback_form

urlpatterns = [
path('feedback/', feedback_form, name='feedback_form'),
]

26
5. **Create Success Page (Optional):**
<!-- success.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Feedback Submitted</title>
</head>
<body>
<h1>Thank you for your feedback!</h1>
</body>
</html>

OUTPUT:

27
Q.10 write a Django web app to use parameters in Views.py
Code:
1. **Define the URL Pattern:**
# urls.py
from django.urls import path
from .views import hello

urlpatterns = [
path('hello/<str:name>/', hello, name='hello'),
]
2. **Create the View Function:**
# views.py
from django.shortcuts import render
from django.http import HttpResponse

def hello(request, name):


return HttpResponse(f"Hello, {name}!")
3. **Run the Development Server:**
python manage.py runserver

OUTPUT:

28
Q.11 write a Django web app using control statements (If,
for etc.)
Code:
1. **Define a Model (Optional):**
# models.py
from django.db import models

class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)

def __str__(self):
return self.name
2. **Create a View:**
# views.py
from django.shortcuts import render
from .models import Product

def product_list(request):
products = Product.objects.all()
return render(request, 'product_list.html', {'products': products})

29
3. **Create a Template:**
<!-- product_list.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Product List</title>
</head>
<body>
<h1>Product List</h1>
<ul>
{% for product in products %}
<li>
<strong>{{ product.name }}</strong>: ${{ product.price }}
{% if product.price > 50 %}
(Expensive)
{% else %}
(Affordable)
{% endif %}
</li>
{% endfor %}
</ul>
</body>
</html>

30
4. **Define URL Mapping:**
# urls.py
from django.urls import path
from .views import product_list

urlpatterns = [
path('products/', product_list, name='product_list'),
]

OUTPUT

31
Q.12 Using blocks in Django Template and Extend base.html
in Templates
Code:
1. **Define Base Template:**
<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<header>
<h1>Welcome to My Website</h1>
</header>

<div id="content">
{% block content %}
{% endblock %}
</div>

<footer>
<p>&copy; 2024 My Website</p>
</footer>
</body>

32
</html>
2. **Extend Base Template:**
<!-- child.html -->
{% extends 'base.html' %}

{% block content %}
<h2>Child Template Content</h2>
<p>This is the content of the child template.</p>
{% endblock %}

# views.py
from django.shortcuts import render

def child_template(request):
return render(request, 'child.html')
# urls.py
from django.urls import path
from .views import child_template

urlpatterns = [
path('child/', child_template, name='child_template'),
]

33
OUTPUT:

34
Q.13 Work with Django humanize.
Steps:
Django's `humanize` module provides a set of template filters and utilities to
make data more human-readable. Let's explore how to use some of the
features provided by `humanize`:

1. **Install Django Humanize:**


pip install django-humanize
2. **Add 'django.contrib.humanize' to Installed Apps:**
INSTALLED_APPS = [
...
'django.contrib.humanize',
...
]
Now, let's explore some of the features provided by `django-humanize`:

- **`ordinal` filter**: Converts an integer to its ordinal representation (1st,


2nd, 3rd, etc.).

- **`intcomma` filter**: Adds commas to an integer for a more readable


display.

- **`apnumber` filter**: Converts an integer to its textual representation (one,


two, three, etc.).

35
- **`naturalday` filter**: Converts a date into a more human-readable format
(e.g., "today", "yesterday", or the day of the week for dates within the past
week).

- **`naturaltime` filter**: Converts a datetime object into a more human-


readable format (e.g., "just now", "3 days ago", etc.).

Views.py
# views.py
from django.shortcuts import render
from datetime import datetime

def my_view(request):
# Assuming some_date and some_datetime are defined here or retrieved
from somewhere
some_date = datetime.now().date() # Example: current date
some_datetime = datetime.now() # Example: current datetime

context = {
'some_date': some_date,
'some_datetime': some_datetime,
}
return render(request, 'my_template.html', context)

Here's how we can use these filters in your Django templates:


<!DOCTYPE html>
<html lang="en">

36
<head>
<meta charset="UTF-8">
<title>Django Humanize Example</title>
</head>
<body>
<h1>Django Humanize Example</h1>

<p>Ordinal representation: {{ 1|ordinal }}</p>


<p>Formatted integer with commas: {{ 10000|intcomma }}</p>
<p>Textual representation of number: {{ 3|apnumber }}</p>
<p>Natural day: {{ some_date|naturalday }}</p>
<p>Natural time: {{ some_datetime|naturaltime }}</p>
</body>
</html>

OUTPUT:

37
Q.14 Work with Django Template built in Tags and Filter
Code:
### Built-in Template Tags:
1. **`if`**: Conditionally render content based on a condition.

{% if condition %}
<!-- Render content if condition is true -->
{% else %}
<!-- Render alternative content if condition is false -->
{% endif %}

2. **`for`**: Loop over a sequence and render content for each item.

{% for item in sequence %}


<!-- Render content for each item in the sequence -->
{% endfor %}

3. **`block` and `extends`**: Define and override blocks in templates to


create a hierarchical structure.
<!-- base.html -->
{% block content %}
<!-- Default content -->
{% endblock %}

38
<!-- child.html -->
{% extends 'base.html' %}
{% block content %}
<!-- Override content specific to this template -->
{% endblock %}

4. **`include`**: Include the content of another template within the current


template.

{% include 'path/to/template.html' %}

### Built-in Template Filters:

1. **`date`**: Format a date or datetime object.


{{ date_value|date:"D d M Y" }}

2. **`length`**: Get the length of a list or string.


{{ list|length }}
3. **`default`**: Display a default value if a variable is not defined or is
`None`.

{{ variable|default:"No value" }}
4. **`lower` and `upper`**: Convert a string to lowercase or uppercase.
{{ string|lower }}
{{ string|upper }}

39
5. **`truncatewords`**: Truncate a string to a specified number of words.

{{ string|truncatewords:10 }}

40
Q 15 Handling 404, 502 pages in Django.
Code:
In Django,we can customize the handling of 404 (Page Not Found) and
500 (Server Error) pages by defining custom error views and templates.
Here's how to handle these errors:

### Handling 404 (Page Not Found) Error:

1. **Define Custom 404 View:**


# views.py
from django.shortcuts import render

def error_404_view(request, exception):


return render(request, '404.html', status=404)
2. **Configure URL Mapping:**
# urls.py
from django.urls import path
from .views import error_404_view

handler404 = error_404_view

urlpatterns = [
# other URL patterns
]

41
3. **Create Custom 404 Template:**

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>404 Page Not Found</title>
<link >
<!-- import Bootstrap -->
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]
alpha3/dist/css/bootstrap.min.css">

<!-- custom css -->


<style>
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
font-family: Arial, sans-serif;
}

.container {
text-align: center;
max-width: 600px;
}

.emoji {
font-size: 8rem;
margin-bottom: 20px;

42
}

h1 {
font-size: 3rem;
margin-bottom: 20px;
}

p {
font-size: 1.5rem;
margin-bottom: 20px;
}

.btn {
font-size: 1.25rem;
padding: 10px 20px;
}
</style>
</head>
<body>
<div class="container">
<div class="emoji">😕</div>
<h1>Oops! Page Not Found</h1>
<p>We couldn't find the page you were looking
for.</p>
<a href="/">Go back to Home</a>
</div>
</body>
</html>

43
OUTPUT:

### Handling 500 (Server Error) Error:

1. **Define Custom 500 View:**


# views.py
from django.shortcuts import render

def error_500_view(request):
return render(request, '500.html', status=500)

44
2. **Configure URL Mapping:*
# urls.py
from django.urls import path
from .views import error_500_view
handler500 = error_500_view

urlpatterns = [
# other URL patterns
]
3. **Create Custom 500 Template:**
<!-- 500.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>500 - Server Error</title>
</head>
<body>
<p>this is a custom 500 page ! </p>
</body>
</html>
OUTPUT

45

You might also like