Django Manika Final (2)
Django Manika Final (2)
ON
DJANGO
Submitted by:
Manika kumari
Enrollment No.: 01196702022
Batch: 2022-2025
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
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
4
6. Activate the virtual environment
7. Install Django
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:
6
Q. 3 create a “Hello World” App in Django.
Code:
2. Define a view
Views.py
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>
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>
{% 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
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)
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'created_at']
list_filter = ['author', 'created_at']
search_fields = ['title', 'content']
admin.site.register(Post, PostAdmin)
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})
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
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>© 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`:
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).
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)
36
<head>
<meta charset="UTF-8">
<title>Django Humanize Example</title>
</head>
<body>
<h1>Django Humanize Example</h1>
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.
38
<!-- child.html -->
{% extends 'base.html' %}
{% block content %}
<!-- Override content specific to this template -->
{% endblock %}
{% include 'path/to/template.html' %}
{{ 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:
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">
.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:
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