Django Lab Manual Complete
Django Lab Manual Complete
Dr Srinivasa Gowda GK
Professor ,Department of CSE .Bangalore
Steps:
1. Install Django using pip:
```
pip install django
```
2. Create a new Django project:
```
django-admin startproject myproject
```
3. Navigate to the project directory:
```
cd myproject
```
4. Run the development server:
```
python manage.py runserver
```
5. Open the browser and go to `http://127.0.0.1:8000/` to see the default Django
welcome page.
Steps:
1. Create a new app using the following command:
```
python manage.py startapp myapp
2
```
2. Add the app to the `INSTALLED_APPS` list in `settings.py`:
```python
INSTALLED_APPS = [
...
'myapp',
]
```
3. Create a view in `myapp/views.py`:
```python
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, world!")
```
4. Map the view to a URL in `myapp/urls.py`:
```python
from django.urls import path
from .views import home
urlpatterns = [
path('', home, name='home'),
]
```
5. Include the app URLs in the project’s `urls.py`:
```python
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
```
6. Run the development server and navigate to the home page to see the message
"Hello, world!".
3
Experiment 3: Working with Models
Objective: To create and work with Django models.
Steps:
1. Define a model in `myapp/models.py`:
```python
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
```
2. Create and apply migrations:
```
python manage.py makemigrations
python manage.py migrate
```
3. Register the model in `myapp/admin.py` to make it accessible in the admin
interface:
```python
from django.contrib import admin
from .models import Item
admin.site.register(Item)
```
4. Create a superuser to access the admin site:
```
python manage.py createsuperuser
```
5. Run the development server and log in to the admin site to add, edit, and delete
`Item` instances.
Steps:
1. Create a `templates` directory inside `myapp` and add a template file `home.html`:
```html
4
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Welcome to the Home Page</h1>
</body>
</html>
```
2. Modify the view in `myapp/views.py` to render the template:
```python
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
```
3. Run the development server and navigate to the home page to see the rendered
template.
Steps:
1. Create a form class in `myapp/forms.py`:
```python
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
```
2. Create a view in `myapp/views.py` to handle the form:
```python
from django.shortcuts import render
from .forms import ContactForm
5
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Process form data
return HttpResponse('Thank you for your message.')
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
```
3. Create a template `contact.html` to display the form:
```html
<!DOCTYPE html>
<html>
<head>
<title>Contact Us</title>
</head>
<body>
<h1>Contact Us</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Send</button>
</form>
</body>
</html>
```
4. Map the view to a URL in `myapp/urls.py`:
```python
from django.urls import path
from .views import contact
urlpatterns = [
path('contact/', contact, name='contact'),
]
```
5. Run the development server, navigate to the contact page, and submit the form to
see the form handling in action.
6
Experiment 6: Admin Interfaces and Data Entry
Objective: To register admin interfaces for student and course models, perform
migrations, and illustrate data entry through admin forms.
Steps:
1. Register the models in `myapp/admin.py`:
```python
from django.contrib import admin
from .models import Student, Course
admin.site.register(Student)
admin.site.register(Course)
```
2. Create and apply migrations:
```
python manage.py makemigrations
python manage.py migrate
```
3. Create a superuser to access the admin site if not already created:
```
python manage.py createsuperuser
```
4. Run the development server and log in to the admin site.
5. Use the admin interface to add, edit, and delete student and course records.
6. Verify the data entry through admin forms by viewing the records in the admin
interface.
Steps:
1. Define a `Project` model in `myapp/models.py`:
```python
from django.db import models
class Project(models.Model):
student = models.ForeignKey('Student', on_delete=models.CASCADE)
7
topic = models.CharField(max_length=100)
languages_used = models.CharField(max_length=200)
duration = models.DurationField()
def __str__(self):
return self.topic
```
2. Create and apply migrations:
```
python manage.py makemigrations
python manage.py migrate
```
3. Register the `Project` model in `myapp/admin.py`:
```python
from .models import Project
admin.site.register(Project)
```
4. Create a model form for `Project` in `myapp/forms.py`:
```python
from django import forms
from .models import Project
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['student', 'topic', 'languages_used', 'duration']
```
5. Create a view in `myapp/views.py` to handle the form:
```python
from django.shortcuts import render, redirect
from .forms import ProjectForm
def add_project(request):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
form.save()
return redirect('project_list')
else:
8
form = ProjectForm()
return render(request, 'add_project.html', {'form': form})
```
6. Create a template `add_project.html` to display the form:
```html
<!DOCTYPE html>
<html>
<head>
<title>Add Project</title>
</head>
<body>
<h1>Add Project</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
</body>
</html>
```
7. Map the view to a URL in `myapp/urls.py`:
```python
from django.urls import path
from .views import add_project
urlpatterns = [
path('add_project/', add_project, name='add_project'),
]
```
8. Run the development server, navigate to the add project page, and submit the
form to see the model form handling in action.
Steps:
1. Define the student list view in `myapp/views.py` using `ListView`:
9
```python
from django.views.generic import ListView, DetailView
from .models import Student
class StudentListView(ListView):
model = Student
template_name = 'student_list.html'
context_object_name = 'students'
```
2. Define the student detail view in `myapp/views.py` using `DetailView`:
```python
class StudentDetailView(DetailView):
model = Student
template_name = 'student_detail.html'
```
3. Create a template `student_list.html` to display the list of students:
```html
<!DOCTYPE html>
<html>
<head>
<title>Student List</title>
</head>
<body>
<h1>Student List</h1>
<ul>
{% for student in students %}
<li><a href="{% url 'student_detail' student.pk %}">{{ student.name
}}</a></li>
{% endfor %}
</ul>
</body>
</html>
```
4. Create a template `student_detail.html` to display student details:
```html
<!DOCTYPE html>
<html>
<head>
<title>Student Detail</title>
</head>
10
<body>
<h1>{{ student.name }}</h1>
<p>Age: {{ student.age }}</p>
<p>Course: {{ student.course }}</p>
<!-- Add other relevant details here -->
</body>
</html>
```
5. Map the views to URLs in `myapp/urls.py`:
```python
from django.urls import path
from .views import StudentListView, StudentDetailView
urlpatterns = [
path('students/', StudentListView.as_view(), name='student_list'),
path('students/<int:pk>/', StudentDetailView.as_view(), name='student_detail'),
]
```
6. Run the development server and navigate to the student list page to see the list of
students. Click on any student name to view their details.
Steps:
1. Install the necessary libraries:
```
pip install reportlab
```
2. Create a view in `myapp/views.py` to generate a CSV file for the `Student` model:
```python
import csv
from django.http import HttpResponse
from .models import Student
def export_students_csv(request):
response = HttpResponse(content_type='text/csv')
11
response['Content-Disposition'] = 'attachment; filename="students.csv"'
writer = csv.writer(response)
writer.writerow(['Name', 'Age', 'Course'])
return response
```
3. Create a view in `myapp/views.py` to generate a PDF file for the `Student` model:
```python
from reportlab.pdfgen import canvas
from django.http import HttpResponse
from .models import Student
def export_students_pdf(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="students.pdf"'
p = canvas.Canvas(response)
students = Student.objects.all()
y = 800
p.showPage()
p.save()
return response
```
4. Map the views to URLs in `myapp/urls.py`:
```python
from django.urls import path
from .views import export_students_csv, export_students_pdf
12
urlpatterns = [
path('export/csv/', export_students_csv, name='export_students_csv'),
path('export/pdf/', export_students_pdf, name='export_students_pdf'),
]
```
5. Run the development server and navigate to the export URLs to download the CSV
and PDF files containing student data.
urlpatterns = [
path('search_student/', search_student, name='search_student'),
path('get_student_courses/', get_student_courses, name='get_student_courses'),
]
```
5. Run the development server and navigate to the search student page to search for
students and display their enrolled courses without page refresh using AJAX.
You can create 5 projects each one for a module in the syllabus . the name of
projects
ACS_DjangoProject__VIsem2024_module01
ACS_DjangoProject__VIsem2024_module02
ACS_DjangoProject__VIsem2024_module03
ACS_DjangoProject__VIsem2024_module04
ACS_DjangoProject__VIsem2024_module05