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

Djanfo LAB

The document provides instructions for creating a Django web application using Python and Django. It includes steps to install Python and Django, create a Django project and app, define views and URLs, create a template with dynamic content, and configure template loading. Key steps are to install Python and Django, create a project and app using Django commands, define views and URLs to map them, create a template file with Django template syntax, render the template from a view, and configure Django's template settings.

Uploaded by

GAURAV MISHRA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Djanfo LAB

The document provides instructions for creating a Django web application using Python and Django. It includes steps to install Python and Django, create a Django project and app, define views and URLs, create a template with dynamic content, and configure template loading. Key steps are to install Python and Django, create a project and app using Django commands, define views and URLs to map them, create a template file with Django template syntax, render the template from a view, and configure Django's template settings.

Uploaded by

GAURAV MISHRA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Web Development with Python and Django

Practical File Questions


(BCAP-218) Lab

1. Install Python including installation of pip, installation and setting up virtual environment,
installation of Django

Ans.

1. Install Python:

• Go to the Python downloads page and download the latest version of Python for your
operating system.
• Follow the installation instructions provided for your operating system.

2. Install pip (Python Package Installer):

• Typically, Python installation comes with pip pre-installed. However, it's good to make sure
it's up-to-date. You can do this by running:

python -m pip install --upgrade pip

3. Install Virtual Environment:


• After installing pip, you can install the virtualenv package globally using pip:

pip install virtualenv

4. Create a Virtual Environment:


• Navigate to the directory where you want to create your project.
• Create a virtual environment using virtualenv. Replace myenv with the name you want for
your virtual environment:

virtualenv myenv

Activate the virtual environment. Activation steps depend on your operating system:

• Windows:

myenv\Scripts\activate

• macOS/Linux:

source myenv/bin/activate

5. Install Django:
• While your virtual environment is activated, you can install Django using pip:

pip install django


6. Verify Django Installation:
• After installation, you can verify that Django is installed correctly by checking its version:

python -m django --version

2. Create a new django project using command line

Ans.

1. Navigate to the directory where you want to create your Django project. Open a terminal
or command prompt and use the cd command to change to the desired directory.

2. Activate your virtual environment (if you haven't already done so). If you followed the
previous steps, you should already have your virtual environment activated. If not, navigate
to the directory where your virtual environment is located and activate it using the
appropriate command for your operating system:

• Windows:

myenv\Scripts\activate

• macOS/Linux:

source myenv/bin/activate

3. Create the Django project: Once your virtual environment is activated, use the django-
admin command to create a new Django project. Replace myproject with the name you
want for your Django project:
django-admin startproject myproject

4. Navigate into the newly created project directory: After running the command above, a
new directory named myproject (or whatever name you provided) will be created. Navigate
into this directory using the cd command:
cd myproject

5. Verify project creation: You can verify that the Django project has been created successfully
by listing the files in the directory:

ls (on Linux/Mac)
dir (on Windows)

3. Create a “Hello World” App in Django

Ans.

1. Navigate to your Django project directory: Open a terminal or command prompt, and
change to the directory where your Django project was created.

2. Create the Django app: Django projects are composed of one or more apps. To create a new
app within your project, use the manage.py script provided by Django:
python manage.py startapp helloworld

3. Define a view: In Django, views are Python functions that take a web request and return a
web response. Open the file helloworld/views.py in your text editor, and define a simple
view:

from django.http import HttpResponse

def hello_world(request):
return HttpResponse("Hello, World!")

4. Map the view to a URL: In Django, you need to define URL patterns to map views to specific
URLs. Open the file helloworld/urls.py, and add the following:

from django.urls import path


from . import views

urlpatterns = [
path('hello/', views.hello_world, name='hello_world'),
]

5. Include the app's URLs in the project: Open the file myproject/urls.py (replace myproject
with the name of your project), and include the URL patterns of your app:

from django.contrib import admin


from django.urls import path, include

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

6. Run the development server: Start the Django development server to see your "Hello
World" app in action:

python manage.py runserver

7. Access the app: Open a web browser and go to http://127.0.0.1:8000/helloworld/hello/.


You should see "Hello, World!" displayed in the browser.
4. Create a Django Form using forms.py

Ans.

1. Navigate to your Django app directory: Open a terminal or command prompt and navigate
to the directory of your Django app where you want to create the form.

2. Create a forms.py file: Inside your app directory, create a file named forms.py.

3. Define your form class: Open forms.py in a text editor and define your form class by
importing forms from django:

from django import forms

class MyForm(forms.Form):
# Define fields for your form
name = forms.CharField(label='Your Name', max_length=100)
email = forms.EmailField(label='Your Email')
message = forms.CharField(label='Your Message', widget=forms.Textarea)

4. Use the form in views: You can now use the form in your views. Open the appropriate
views.py file and import the form you created:

from .forms import MyForm


from django.shortcuts import render

def my_view(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
# Process the form data
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
# Additional processing...
else:
form = MyForm()
return render(request, 'my_template.html', {'form': form})

5. Render the form in a template: Create a template file (e.g., my_template.html) in your
app's templates directory and render the form using Django template tags:

<!-- my_template.html -->


<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>

6. Include the URL for your view: Make sure you have a URL pattern set up in your app's
urls.py file to map to the view where your form is used.
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,

Ans. To create a Django app using Django Templates features, including creating template
objects, rendering a template, using multiple contexts, context variable lookup, playing with
context objects, template loading, and including template tags, follow these steps:

1. Create a Template: Create a template file inside your app's templates directory. Let's call it
index.html. This template will use Django template syntax to render dynamic content.

<!-- templates/index.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<h1>Welcome to my website</h1>
<p>This is a simple Django template.</p>
<p>Variable value: {{ my_variable }}</p>
<p>Loop Example:</p>
<ul>
{% for item in my_list %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>

2. Create a View: Create a view function in your views.py file. This function will render the
template and pass data to it.

# views.py
from django.shortcuts import render

def index(request):
my_variable = "Hello, Django!"
my_list = ["Item 1", "Item 2", "Item 3"]
return render(request, 'index.html', {'my_variable': my_variable, 'my_list': my_list})

3. Map the View to a URL: Define a URL pattern in your app's urls.py to map the view function
to a URL.

# urls.py
from django.urls import path
from .views import index
urlpatterns = [
path('', index, name='index'),
]

4. Configure Template Loading: Ensure that Django knows where to find your templates. Add
the TEMPLATES setting in your project's settings.py to specify the directory where your
templates are stored.

# settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

5. Use the Template: Use the {% include %} tag to include another template within your main
template. For example, let's create a header.html template and include it in index.html.

<!-- templates/header.html -->


<header>
<h2>This is the header</h2>
</header>

<!-- templates/index.html -->


{% include 'header.html' %}
<!-- rest of your index.html template -->

6. Run the Development Server: Start the Django development server and navigate to the URL
mapped to your view. You should see the rendered template with dynamic content and
included templates.
6. App to connect templates with models to serve data dynamically

Ans. To create a Django app that connects templates with models to serve data dynamically,
follow these steps:

1. Define Models: Define your data models in the models.py file of your Django app. These
models will represent the data you want to serve dynamically.

# 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)
description = models.TextField()

def __str__(self):
return self.name

2. Create Views: Create view functions in your views.py file to handle requests and interact
with the models to retrieve data.

# 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})

3. Create Templates: Create template files to display the dynamic data. For example, let's
create a template called product_list.html.

<!-- templates/product_list.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product List</title>
</head>
<body>
<h1>Product List</h1>
<ul>
{% for product in products %}
<li>{{ product.name }} - ${{ product.price }}</li>
<p>{{ product.description }}</p>
{% endfor %}
</ul>
</body>
</html>
4. Map Views to URLs: Define URL patterns in your app's urls.py file to map the views to
specific URLs.

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

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

5. Run Migrations: Apply migrations to create database tables for your models.

python manage.py makemigrations


python manage.py migrate

6. Populate Data: If needed, use Django admin or custom management commands to populate
your database with initial data.

7. Run the Development Server: Start the Django development server and navigate to the URL
mapped to your view (e.g., http://127.0.0.1:8000/products/). You should see the list of
products rendered dynamically from the database.

7. Write a Django web app using control statements (If, for etc.)

Ans. To write a Django web app utilizing control statements like if and for, you can follow these
steps to create a simple example:

1. Define a Model: Let's start by defining a simple model to represent some data. In this
example, we'll create a Person model with fields for name and age.

# models.py
from django.db import models

class Person(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()

def __str__(self):
return self.name

2. Create Views: Next, create a view that will query the database and pass the data to a
template.

# views.py
from django.shortcuts import render
from .models import Person

def person_list(request):
people = Person.objects.all()
return render(request, 'person_list.html', {'people': people})

3. Create a Template: Now, create a template to display the data. We'll use control statements
like for loop and if statement to iterate over the list of people and conditionally display their
information.

<!-- templates/person_list.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Person List</title>
</head>
<body>
<h1>People List</h1>
<ul>
{% for person in people %}
<li>
Name: {{ person.name }}<br>
{% if person.age >= 18 %}
Age: {{ person.age }} (Adult)
{% else %}
Age: {{ person.age }} (Minor)
{% endif %}
</li>
{% endfor %}
</ul>
</body>
</html>

4. Map View to URL: Define a URL pattern in your app's urls.py to map the view to a specific
URL.

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

urlpatterns = [
path('people/', person_list, name='person_list'),
]

5. Run Migrations: Apply migrations to create database tables for your models.

python manage.py makemigrations


python manage.py migrate
6. Create and Populate Data: If needed, use Django admin or custom management commands
to populate your database with initial data.

7. Run the Development Server: Start the Django development server and navigate to the URL
mapped to your view (e.g., http://127.0.0.1:8000/people/). You should see the list of
people displayed, with their ages categorized as adults or minors based on the if statement
in the template.

8. Create a Dynamic Feedback form with validations

Ans.

1. Define Model: Start by defining a model to represent the feedback data. This model will
include fields for the feedback attributes.

# models.py
from django.db import models

class Feedback(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
message = models.TextField()
rating = models.IntegerField()

def __str__(self):
return self.name

2. Create Form: Create a Django form class that corresponds to the model you defined. You
can add validation rules to this form.

# forms.py
from django import forms
from .models import Feedback

class FeedbackForm(forms.ModelForm):
class Meta:
model = Feedback
fields = ['name', 'email', 'message', 'rating']

def clean_rating(self):
rating = self.cleaned_data.get('rating')
if rating < 1 or rating > 5:
raise forms.ValidationError("Rating must be between 1 and 5.")
return rating

3. Create View: Create a view that handles the form submission and renders the form
template.

# 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():
form.save()
# Redirect to a success page or display a success message
else:
form = FeedbackForm()
return render(request, 'feedback_form.html', {'form': form})

4. Create Template: Create a template to display the feedback form.

<!-- templates/feedback_form.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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>

5. Map View to URL: Define a URL pattern in your app's urls.py to map the view to a specific
URL.

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

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

6. Run Migrations: Apply migrations to create database tables for your models.

python manage.py makemigrations


python manage.py migrate

7. Run the Development Server: Start the Django development server and navigate to the URL
mapped to your feedback form (e.g., http://127.0.0.1:8000/feedback/). You should see the
feedback form rendered. Fill out the form and submit it to test the validations.
9. Using blocks in Django Template and Extend base.html in Templates

Ans.

1. Create a Base Template (base.html): Create a base template that contains the common
elements you want to reuse across multiple pages. For example, you might have a header,
footer, and a navigation menu.

<!-- templates/base.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<header>
<h1>Welcome to My Website</h1>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about/">About</a></li>
<li><a href="/contact/">Contact</a></li>
</ul>
</nav>
</header>

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

<footer>
<p>&copy; 2024 My Website. All rights reserved.</p>
</footer>
</body>
</html>

2. Extend the Base Template in Other Templates: Create other templates in your app, and use
the {% extends %} tag to extend the base template. You can override blocks defined in the
base template as needed.
• For example, let's create an about.html template:
<!-- templates/about.html -->
{% extends 'base.html' %}

{% block title %}About Us{% endblock %}

{% block content %}
<h2>About Us</h2>
<p>This is the about page content.</p>
{% endblock %}

• Similarly, you can create a contact.html template:

<!-- templates/contact.html -->


{% extends 'base.html' %}

{% block title %}Contact Us{% endblock %}

{% block content %}
<h2>Contact Us</h2>
<p>This is the contact page content.</p>
{% endblock %}

3. Configure URLs: Configure URLs in your app's urls.py to map views to these templates.
4. Run the Development Server: Start the Django development server and navigate to the
URLs mapped to your views. Django will render the templates by extending the base
template and replacing the content block with the specific content for each page.

10. Creating a Feedback Form with database submission

Ans.

1. Define a Model: Define a model to represent the feedback data. This model will map to a
database table where feedback submissions will be stored.
# models.py
from django.db import models

class Feedback(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
message = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.name

2. Create a Form: Create a form using Django's ModelForm to collect feedback from users.

# forms.py
from django import forms
from .models import Feedback

class FeedbackForm(forms.ModelForm):
class Meta:
model = Feedback
fields = ['name', 'email', 'message']
3. Create a View: Create a view to handle the feedback form submission.

# views.py
from django.shortcuts import render, redirect
from .forms import FeedbackForm

def feedback(request):
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
form.save()
return redirect('thank_you') # Redirect to a thank you page after successful
submission
else:
form = FeedbackForm()
return render(request, 'feedback.html', {'form': form})

4. Create a Template: Create a template for the feedback form where users can submit their
feedback.

<!-- templates/feedback.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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>

5. Create a Thank You Page Template: Optionally, create a thank you page template to display
a message after successful submission.

<!-- templates/thank_you.html -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Thank You</title>
</head>
<body>
<h1>Thank You for Your Feedback!</h1>
<p>We appreciate your feedback. Thank you for taking the time to submit it.</p>
</body>
</html>

6. Configure URLs: Configure a URL in your app's urls.py to map the feedback view.
7. Run Migrations: Apply migrations to create database tables for your models.

python manage.py makemigrations


python manage.py migrate

8. Run the Development Server: Start the Django development server and navigate to the URL
mapped to your feedback form. Users can now submit feedback, and their submissions will
be stored in the database.

You might also like