Djanfo LAB
Djanfo 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.
• 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:
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:
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)
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:
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:
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:
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:
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:
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:
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:
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.
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.
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.
# 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.
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.
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.
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.
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})
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.
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.
<div class="content">
{% block content %}
{% endblock %}
</div>
<footer>
<p>© 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 content %}
<h2>About Us</h2>
<p>This is the about page content.</p>
{% 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.
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.
5. Create a Thank You Page Template: Optionally, create a thank you page template to display
a message after successful submission.
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.
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.