0% found this document useful (0 votes)
166 views46 pages

Experiment-01-08 Full Stack Django

LAB MANUAL

Uploaded by

Resh Reshma
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)
166 views46 pages

Experiment-01-08 Full Stack Django

LAB MANUAL

Uploaded by

Resh Reshma
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/ 46

21CS62 | Full Stack Development

FULL STACK DEVELOPMENT

 Full Stack Development refers to the practice of developing both the front-end (client- side) and
back-end (server-side) portions of web applications.
 A full stack developer is proficient in working with both the front-end and back-end
technologies, allowing them to build complete web applications independently or as part of a
team.
Technologies used in full stack development
Front-End Technologies:
 HTML (Hypertext Markup Language): Used for structuring web pages.
 CSS (Cascading Style Sheets): Used for styling the appearance of web pages.
 JavaScript: A programming language used for adding interactivity and dynamic behavior to web
pages.
 Front-end frameworks/libraries such as React.js, AngularJS, or Vue.js: These provide tools and
utilities for building user interfaces and managing application state.

Back-End Technologies:
 Server-side languages like JavaScript (Node.js), Python (Django, Flask), Ruby (Ruby
 on Rails), Java (Spring Boot), or PHP (Laravel), C#(.Net Framework), java(Servlets)
 Databases such as MySQL, PostgreSQL, MongoDB, or Firebase for storing and
 managing data.
 Web servers like Apache or Nginx or IIS or Tomcat or Caddy(with built in support for
 https) for handling HTTP requests.

Development Tools and Environment:


 Version control systems like Git for managing code changes.
 Integrated Development Environments (IDEs) such as Visual Studio Code, Sublime Text, or
Atom.
What is Django?
 Django is a free and open source web application framework which offers fast and effective
dynamic website development.
 It is written using python.
 It follows MVT (model, view and template architecture)
Framework
 A framework is a pre-built collection of libraries, modules, and tools that provides a structured
approach to developing software applications.
 Django is a web development framework. AngularJS is a Web Frontend development

Dept of CSE, EWIT Page 2


21CS62 | Full Stack Development

framework React is a Web frontend development library.

Django MVT
The MVT is a software design pattern which includes three important components
Model, View and Template.
 The Model helps to handle database. It is a data access layer which handles the data.
 The Template is a presentation layer which handles User Interface part completely.
 The View is used to execute the business logic and interact with a model to carry data and
renders a template.

Dept of CSE, EWIT Page 3


21CS62 | Full Stack Development

Experiment-01

Installation of Python, Django and Visual Studio code editors can be demonstrated.

Python

 Python is a popular high-level, general-use programming language.


 Python is a programming language that enables rapid development as well as more
effective system integration.
 Python has two main different versions: Python 2 and Python 3. Both are really different.

Here are the steps you can follow to download Python: Steps to Download & Install Python

Visit the linkhttps://www.python.orgto download the latest release of Python.

Dept of CSE, EWIT Page 4


21CS62 | Full Stack Development

Step - 1: Select the Python's version to download.

Click on the download button to download the exe file of Python.

If in case you want to download the specific version of Python. Then, you can scroll down further
below to see different versions from 2 and 3 respectively. Click on download button right next to
the version number you want to download.

Dept of CSE, EWIT Page 5


21CS62 | Full Stack Development

Step - 2: Click on the Install Now

uble-click the executable file, which is downloaded.

The following window will open. Click on the Add Path check box, it will set the Python path
automatically.

Now, Select Customize installation and proceed. We can also click on the customize installation
to choose desired location and features. Other important thing is installing launcher for the all user
must be checked.

Dept of CSE, EWIT Page 6


21CS62 | Full Stack Development

Step - 3 Installation in Process

The set up is in progress. All the python libraries, packages, and other python default files will be
installed in our system. Once the installation is successful, the following page will appear saying
" Setup was successful ".

Dept of CSE, EWIT Page 7


21CS62 | Full Stack Development

Step - 4: Verifying the Python Installation

To verify whether the python is installed or not in our system, we have to do the following.

o Go to "Start" button, and search " cmd ".


o Then type, " python - - version ".
o If python is successfully installed, then we can see the version of the python installed.
o If not installed, then it will print the error as " 'python' is not recognized as an internal or
external command, operable program or batch file. ".

We are ready to work with the Python.

Dept of CSE, EWIT Page 8


21CS62 | Full Stack Development

Here are the steps you can follow: Steps to Download & Install VS Code

Step – 1: Open Google and type Visual Studio Code download in the search bar.

Step – 2: Click on the below highlighted link for any OS.

Dept of CSE, EWIT Page 9


21CS62 | Full Stack Development

Step – 3: Now, select the respective OS. In this case we are selecting Windows.

Step – 4: The file will be downloaded onto your system. Open the file and then click on Install.
After downloading the VS Code file, the official site will display a Thanks message for
downloading the file.

Dept of CSE, EWIT Page 10


21CS62 | Full Stack Development

Step – 5: Now accept the license agreement.

Dept of CSE, EWIT Page 11


21CS62 | Full Stack Development

Step – 6: Then it prompts for the file location, where you want to save the VS Code file.
Browse the location and then click on Next.

Step – 7: Next, you see the prompt for the additional task which we want the VS Code to
perform. At this step, choose the default settings and then click on next.

Dept of CSE, EWIT Page 12


21CS62 | Full Stack Development

Step – 8: The next prompt is how you want the VS Code on your startup. Change
according to your convenience and click on Next.

Step – 9: The installation of VS Code will now begin.

Dept of CSE, EWIT Page 13


21CS62 | Full Stack Development

Step – 10: At this step, we have completed installing VS Code, click on Finish.

Dept of CSE, EWIT Page 14


21CS62 | Full Stack Development

Step – 11: Now that VS Code installation is successful, the page appears as below:

We can change the look as per our choice and continue working on it

Dept of CSE, EWIT Page 15


21CS62 | Full Stack Development

Experiment-02
Creation of virtual environment, Django project and App should be demonstrated.

Steps to Create Virtual Environment, Django Project and App

Step-01: Open Visual Studio Code

Step-02: Create a new folder for your project

In VS Code, go to File > Open... and create a new folder or select an existing folder where you
want to create your Django project.

Dept of CSE, EWIT Page 16


21CS62 | Full Stack Development

Step-03: Open the integrated terminal

In VS Code, go to View > Terminal or use the keyboard shortcut Ctrl+`` (Windows/Linux) or
Cmd+`' (macOS) to open the integrated terminal.

Step-03: Create a virtual environment

In the terminal, run the following command to create a new virtual environment:
python -m venv [environment Name] OR mkvirtualenv [environment Name]

Dept of CSE, EWIT Page 17


21CS62 | Full Stack Development

Step-04: Activate the virtual environment

Step-05: Install Django

With the virtual environment active, install Django by running the following command in the
terminal: pip install django

Dept of CSE, EWIT Page 18


21CS62 | Full Stack Development

Step-06: Create a new Django project

Run the following command to create a new Django project:

django-admin startproject myproject [change Project name as You Desired]

Step-07: Create a new Django app

In the VS Code terminal, navigate to your project directory:

cd myproject [change Project name as You Desired]

Dept of CSE, EWIT Page 19


21CS62 | Full Stack Development

Create a new Django app by running the following command

python manage.py startapp myapp

[Replace myapp with the name you want to give to your app.]

Step-08: Add the app to the INSTALLED_APPS list

In the VS Code file explorer, locate the settings.py file (usually located in the myproject
directory) and open it.

Locate the INSTALLED_APPS list and add the name of your new app to the list

Dept of CSE, EWIT Page 20


21CS62 | Full Stack Development

Here is the Django project structure that you wanted to create

after creating your Django app, the next step is to create database migrations for your
app's models (if you have any defined). Here's how you can do that using the python
manage.py makemigrations command in Visual Studio Code (VS Code)

Dept of CSE, EWIT Page 21


21CS62 | Full Stack Development

Step-08: Apply the migrations

Once you've reviewed the migration files and are ready to apply the changes to your
database, run the following command in the terminal:

Step-09: Run Your Project

Here's how you can run the Django development server using the
python manage.py runserver command in Visual Studio Code (VS Code)

Check the server output

The terminal will display the URL where the development server is running, typically
http://127.0.0.1:8000/. It will also show any startup logs or warnings, if any. Open
the development server in your browser Copy the URL from the terminal output (e.g.,
http://127.0.0.1:8000/) and paste it into your web browser's address bar.

Dept of CSE, EWIT Page 22


21CS62 | Full Stack Development

Here Displays the Development Server After Running Server

Dept of CSE, EWIT Page 23


21CS62 | Full Stack Development

Experiment-03
Develop a Django app that displays current date and time in server.

Step-01: This app will be created in the Django project we made earlier.

Step-02: Add the app to INSTALLED_APPS

Open the settings.py file in your project's directory (e.g., myproject/settings.py).


Locate the INSTALLED_APPS list and add the name of your new app to the list:

Step-03: Create a view function

• Open the views.py file in your Django app's directory (e.g., datetimeapp/views.py).
• Import the necessary modules at the top of the file
• Create a new view function that will handle the request and render the date and time:

from django.shortcuts import render


from django.http import HttpResponse
from datetime import datetime

def current_datetime(request):
now =datetime.now ()
html = f"<html><body><h1>Current Date and Time:</h1><p>{now}</p></body></html>"
return HttpResponse(html)

Step-05: Map the view function to a URL

Dept of CSE, EWIT Page 24


21CS62 | Full Stack Development

• Open the urls.py file in your Django app's directory (e.g., datetimeapp/urls.py).
• Import the view function at the top of the file
• Add a new URL pattern to the urlpatterns list

from django. urls import path


from. import views
urlpatterns = [
path ('', views. current_datetime, name='current_datetime'),
]

This maps the current_datetime view function to the root URL (/).

Step-06: Include the app's URLs in the project's URL patterns

• Open the urls.py file in your project's directory (e.g., fullstack_project/urls.py).


• Import the include function from django. urls and the path function from django. Urls
• Add a new URL pattern to the urlpatterns list
• This includes the URL patterns from your app's urls.py file.

from django.contrib import admin


from django.urls import path, include
# Import include
urlpatterns = [
path('admin/', admin.site.urls),
path('datetimeapp /', include('datetimeapp.urls')), # Include your app's URLs
]

Step-07: Run the development server


• In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
• Run the development server
python manage.py runserver
• Open your web browser and visit http://127.0.0.1:8000/.

Dept of CSE, EWIT Page 25


21CS62 | Full Stack Development

Output:

Dept of CSE, EWIT Page 26


21CS62 | Full Stack Development

Experiment-04

Develop a Django app that displays date and time four hours ahead and four hours
before as an offset of current date and time in server.

Step-01: This app will be created in the Django project we made earlier.

Step-02: Add the app to INSTALLED_APPS

Open the settings.py file in your project's directory (e.g., myproject/settings.py).

Locate the INSTALLED_APPS list and add the name of your new app to the list:

Dept of CSE, EWIT Page 27


21CS62 | Full Stack Development

Step-03: Create a view function


 Open the views.py file in your Django app's directory (e.g.,
fourdate_timeapp/views.py).
 Import the necessary modules at the top of the file
 Create a new view function that will handle the request and render the date and time:

from django.http import HttpResponse


from datetime import datetime, timedelta

def datetime_with_offsets(request):
now = datetime.now()
offset_hours = 4
# Calculate dates with offsets
four_hours_ahead = now + timedelta(hours=offset_hours)
four_hours_before = now - timedelta(hours=offset_hours)
html = f"<html><body><h1>Current Date and Time with Offsets:</h1>" \
f"<p>Current: {now}</p>" \
f"<p>Four Hours Ahead: {four_hours_ahead}</p>" \
f"<p>Four Hours Before: {four_hours_before}</p></body></html>"
return HttpResponse(html)

Step-04: Map the view function to a URL

 Open the urls.py file in your Django app's directory (e.g., fourdate_timeapp/urls.py).
 Import the view function at the top of the file
 Add a new URL pattern to the urlpatterns list

from django.urls import path


from . import views

urlpatterns = [
path('datetime-offsets/', views. datetime_with_offsets, name= ‘datetime_with_offsets '),
]
Step-05: Include the app's URLs in the project's URL patterns

 Open the urls.py file in your project's directory (e.g., fullstack_project/urls.py).


 Import the include function from django. urls and the path function from django. urls:

Dept of CSE, EWIT Page 28


21CS62 | Full Stack Development

from django.contrib import admin


from django.urls import path, include
# Import include
urlpatterns = [
path('admin/', admin.site.urls),
path(' fourdate_timeapp /', include(' fourdate_timeapp.urls')),
# Include your app's URLs
]

Step-06: Run the development server

 In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
 Run the development server

python manage.py runserver

 Open your web browser and visit http://127.0.0.1:8000/.


 Type or copy this http://127.0.0.1:8000/datetime-offsets/

Output:

Dept of CSE, EWIT Page 29


21CS62 | Full Stack Development

Develop a simple Django app that displays an unordered list of fruits and ordered list of

selected students for an event.

Step-01: This app will be created in the Django project we made earlier.

Step-02: Add the app to INSTALLED_APPS

Open the settings.py file in your project's directory (e.g., myproject/settings.py).

Locate the INSTALLED_APPS list and add the name of your new app to the list:

Step-03: Create a view function

 Open the views.py file in your Django app's directory (e.g.,


listfruitapp/views.py).
 Create a new view function that will handle the request and render :

from django.shortcuts import render

Dept of CSE, EWIT Page 30


21CS62 | Full Stack Development

def home(request):
fruits = ['Apple', 'Banana', 'Orange', 'Mango', 'Pineapple']
students = ['John', 'Jane', 'Mike', 'Sarah', 'Tom']
context =
{ 'fruits':
fruits,
'students': students,
}
return render(request, 'home.html', context)

 Here, we define a view function home that creates two lists: fruits and students. These lists are
then passed to the template as a context dictionary.

Step-04: Create a new template

 In your app's directory (e.g., listfruitapp), create a new folder named templates (if it doesn't
already exist).
 Inside the templates folder, create another folder with the same name as your app (e.g.,
listfruitapp).
 create a new file named home.html.
 Open home.html and add the following code.

<!DOCTYPE html>
<html>
<head>
<title>Fruits and Students</title>
</head>
<body>

<h1>Fruits</h1>
<ul class="list-group list-container">
{% for fruit in fruits %}
<li class="list-group-item">{{ fruit }}</li>
{% endfor %}
</ul>
<h1>Selected Students</h1>
<ol class="list-group list-container">

Dept of CSE, EWIT Page 31


21CS62 | Full Stack Development
{% for student in students %}
<li class="list-group-item">{{ student }}</li>
{% endfor %}
</ol>
</body>
</html>

 In this template, we use Django's template tags to loop through the fruits and students lists and
render them as an unordered list and an ordered list, respectively.
Step-05: Map the view function to a URL
 Open the urls.py file in your Django app's directory (e.g., listfruitapp/urls.py).
 Import the view function at the top of the file
 Add a new URL pattern to the urlpatterns list
from django.urls import path
from . import views
urlpatterns = [
path('home/', views.home, name='home'),
]

Step-06: Include the app's URLs in the project's URL patterns


 Open the urls.py file in your project's directory (e.g., fullstack_project/urls.py).
 Import the include function from django. urls and the path function from django. urls:

from django.urls import include, path


 Add a new URL pattern to the urlpatterns list
path('', include(listfruitapp.urls')),

 This includes the URL patterns from your app's urls.py file.
Step-07: Run the development server
 In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py). Run the development server

python manage.py runserver


 Open your web browser and visit http://127.0.0.1:8000/.

Output:

Dept of CSE, EWIT Page 32


21CS62 | Full Stack Development

Experiment-06

Develop a layout.html with a suitable header (containing navigation menu) and footer with
copyright and developer information. Inherit this layout.html and create 3 additionalpages:
contact us, About Us and Home page of any website.
Step 1: Set up your Django APP
Create a new Django app within the project:

python manage.py startapp portfolioapp

Step-02: Add the app to INSTALLED_APPS

Open the settings.py file in your project's directory (e.g., myproject/settings.py). Locate
the INSTALLED_APPS list and add the name of your new app to the list

Step-03: Create a new template

 Inside the portfolioapp/templates/ portfolio directory, create the following files:


layout.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>
<!-- Add your CSS and JS links here -->
</head>
<body>
<header>
<nav>
<ul>
<li><a href="{% url 'home' %}">Home</a></li>
<li><a href="{% url 'about' %}">About Us</a></li>
<li><a href="{% url 'contact' %}">Contact Us</a></li>
</ul>
</nav>
</header>
<main>
{% block content %}
{% endblock %}
</main>

Dept of CSE, EWIT Page 33


21CS62 | Full Stack Development

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

home.html

{% extends 'layout.html' %}

{% block title %}Home - My Website{% endblock %}

{% block content %}

<h1>Welcome to My Website</h1>

<!-- Add home page content here -->

{% endblock %}

Contact_us.html

{% extends 'layout.html' %}

{% block title %}Contact Us - My Website{% endblock %}

{% block content %}

<h1>Contact Us</h1>

<!-- Add contact us page content here -->

{% endblock %}

About_us.html

{% extends 'layout.html' %}

{% block title %}About Us - My Website{% endblock %}

{% block content %}

Dept of CSE, EWIT Page 34


21CS62 | Full Stack Development

<h1>About Us</h1>

<!-- Add about us page content here -->

{% endblock %}
Step-04: Create a view function

 Open the views.py file in your Django app's directory

from django.shortcuts import render

def home(request):
return render(request, 'home.html')

def about(request):
return render(request, 'about_us.html')

def contact(request):
return render(request, 'contact_us.html')

Step-05: Map the view function to a URL


 Open the urls.py file in your Django app's directory
 import the view function at the top of the file
 Add a new URL pattern to the urlpatterns list

from django.urls import path


from . import views
urlpatterns = [
path('home/', views.home, name='home'),
path('about/', views.about, name='about'),
path('contact/', views.contact, name='contact'),
]

Step-06: Include the app's URLs in the project's URL patterns


 Open the urls.py file in your project's directory (e.g., myproject/urls.py).
 Import the include function from django. urls and the path function from django. urls:
 Add a new URL pattern to the urlpatterns list
from django.urls import include,
path('', include(portfolioapp.urls')),

Dept of CSE, EWIT Page 35


21CS62 | Full Stack Development

Step-07: Run the development server

 In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
 Run the development server

python manage.py runserver

 Open your web browser and visit http://127.0.0.1:8000/.

Output:

Dept of CSE, EWIT Page 36


21CS62 | Full Stack Development

Experiment-07

Develop a Django app that performs student registration to a course. It should also display list of
students registered for any selected course. Create students and course as models with enrolment
as Many To Many field.

Step 1: Set up your Django Project


First, ensure you have Django installed. If not, install it using:

pip install django

Create a new Django project:


django-admin startproject school
cd school
Create a new Django app within the project:

python manage.py startapp courses

Step 2: Define Models


In the courses app, define the models for Student and Course in models.py.

# courses/models.py

from django.db import models

class Student(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(unique=True)

def str (self):


return f"{self.first_name} {self.last_name}"

class Course(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
students = models.ManyToManyField(Student, related_name='courses', blank=True)

def str (self):


return self.name

Dept of CSE, EWIT Page 37


21CS62 | Full Stack Development

Step 3: Create Views

Create views for registering students, enrolling in courses, and listing students in a course.

# courses/views.py

from django.shortcuts import render, get_object_or_404, redirect


from .models import Student, Course

def student_registration(request):
if request.method == 'POST':
first_name = request.POST['first_name']
last_name = request.POST['last_name']
email = request.POST['email']
student = Student(first_name=first_name, last_name=last_name, email=email)
student.save()
return redirect('course_list')
return render(request, 'courses/student_registration.html')

def enroll_course(request):
if request.method == 'POST':
student_id = request.POST['student_id']
course_id = request.POST['course_id']
student = get_object_or_404(Student, id=student_id)
course = get_object_or_404(Course, id=course_id)
course.students.add(student)
return redirect('course_list')
students = Student.objects.all()
courses = Course.objects.all()
return render(request, 'courses/enroll_course.html', {'students': students, 'courses': courses})

def course_list(request):

Dept of CSE, EWIT Page 38


21CS62 | Full Stack Development

courses = Course.objects.all()
return render(request, 'courses/course_list.html', {'courses': courses})

def course_detail(request, course_id):


course = get_object_or_404(Course, id=course_id)
students = course.students.all()
return render(request, 'courses/course_detail.html', {'course': course, 'students': students})

def add_course(request):
if request.method == 'POST':
name = request.POST['name']
description = request.POST['description']
course = Course(name=name, description=description)
course.save()
return redirect('course_list')
return render(request, 'courses/add_course.html')

Step 4: Create Templates


Create the templates for student registration, course enrollment, course list, and course detail.

student_registration.html

<!-- templates/courses/student_registration.html -->

<!DOCTYPE html>
<html>
<head>
<title>Student Registration</title>
</head>
<body>
<h1>Register Student</h1>
<form method="post">
{% csrf_token %}
<p>First name: <input type="text" name="first_name" required></p>
<p>Last name: <input type="text" name="last_name" required></p>
<p>Email: <input type="email" name="email" required></p>
<button type="submit">Register</button>
</form>
</body>
</html>

enroll_course.html
<!-- templates/courses/enroll_course.html -->

Dept of CSE, EWIT Page 39


21CS62 | Full Stack Development

<!DOCTYPE html>
<html>
<head>
<title>Enroll in Course</title>
</head>
<body>
<h1>Enroll in Course</h1>
<form method="post">
{% csrf_token %}
<p>Select Student:
<select name="student_id">
{% for student in students %}
<option value="{{ student.id }}">{{ student }}</option>
{% endfor %}
</select>
</p>
<p>Select Course:
<select name="course_id">
{% for course in courses %}
<option value="{{ course.id }}">{{ course.name }}</option>
{% endfor %}
</select>
</p>
<button type="submit">Enroll</button>
</form>
</body>
</html>

course_list.html

<!-- templates/courses/course_list.html -->

<!DOCTYPE html>
<html>
<head>
<title>Course List</title>
</head>
<body>
<h1>Courses</h1>
<ul>
{% for course in courses %}
<li><a href="{% url 'course_detail' course.id %}">{{ course.name }}</a></li>
{% endfor %}
</ul>
</body>

Dept of CSE, EWIT Page 40


21CS62 | Full Stack Development

</html>

course_detail.html

<!-- templates/courses/course_detail.html -->

<!DOCTYPE html>
<html>
<head>
<title>{{ course.name }}</title>
</head>
<body>
<h1>{{ course.name }}</h1>
<p>{{ course.description }}</p>
<h2>Enrolled Students</h2>
<ul>
{% for student in students %}
<li>{{ student }}</li>
{% endfor %}
</ul>
</body>
</html>

Add_course.html
<!-- templates/courses/add_course.html -->

<!DOCTYPE html>
<html>
<head>
<title>Add Course</title>
</head>
<body>
<h1>Add Course</h1>
<form method="post">
{% csrf_token %}
<p>Course Name: <input type="text" name="name" required></p>
<p>Course Description: <textarea name="description" required></textarea></p>
<button type="submit">Add Course</button>
</form>
</body>
</html>

Dept of CSE, EWIT Page 41


21CS62 | Full Stack Development

Step 6: Define URLs


Add URLs for the views in courses/urls.py.

# courses/urls.py

from django.urls import path


from . import views

urlpatterns = [
path('register/', views.student_registration, name='student_registration'),
path('enroll/', views.enroll_course, name='enroll_course'),
path('courses/', views.course_list, name='course_list'),
path('courses/<int:course_id>/', views.course_detail, name='course_detail'),
path('add_course/', views.add_course, name='add_course'),
]

Include the courses URLs in the main urls.py file of the project.

# Main_ project/urls.py

from django.contrib import admin


from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('courses.urls')),
]
Step 7: Apply Migrations
Run the migrations to create the database schema.

python manage.py makemigrations


python manage.py migrate

Step 8: Run the Server


Finally, run the development server.

python manage.py runserver


You can now access the application at http://localhost:8000. Use the provided views to register students,
enroll them in courses, and view the list of students enrolled in each course.

Output:

Dept of CSE, EWIT Page 42


21CS62 | Full Stack Development

Experiment-08

For student and course models created in Lab experiment for Module2, register admin

interfaces, perform migrations and illustrate data entry through admin forms.

Step-01: Register models in the admin site.


from django.contrib import admin
from .models import Course, Student
@admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
list_display = ('name', 'description')

@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):

list_display = ('first_name', 'last_name', 'email')

filter_horizontal = ('courses',)

 In this code, we've registered the Course and Student models with the Django admin site.
 We've also specified the fields to be displayed in the list view for each model using the
list_display attribute.
 For the StudentAdmin class, we've added the filter_horizontal attribute to display the courses
field (which is a many-to-many relationship) as a horizontal filter in the admin interface.

Step-02: Create and apply migrations

python manage.py makemigrations

python manage.py migrate

Dept of CSE, EWIT Page 43


21CS62 | Full Stack Development

Step-03: Create a superuser


 If you haven't already created a superuser for your project, you'll need to do so to accessthe
admin interface.
 In your terminal or command prompt, run the following command

python manage.py createsuperuser

Provide Superuser Information: You will be prompted to enter the following information:

 Username: The username for the superuser.


 Email Address: The email address for the superuser.
 Password: The password for the superuser. You will be asked to enter it twice for confirmation.

Example:

Username (leave blank to use 'your-username'): admin


Email address: [email protected]
Password: ********
Password (again): ********
Superuser created successfully.
Step-04: Run the development server
python manage.py runserver

• Open your web browser and visit http://127.0.0.1:8000/.


Output:
Log in to the admin interface

 Back in your web browser, enter the superuser credentials you just created and log in to
the admin interface.

Dept of CSE, EWIT Page 44


21CS62 | Full Stack Development

Add data through admin forms

Once you're logged in to the admin interface, you'll see the "Courses" and "Students" sections inthe
left sidebar. Click on "Courses" to add a new course.

 Click on the "Add course" button in the top-right corner.


 Fill in the "Name" and "Description" fields for the new course.
 Click the "Save" button to create the new course.

Next, click on "Students" in the left sidebar to add a new student.

 Click on the "Add student" button in the top-right corner.


 Fill in the "First name", "Last name", and "Email" fields for the new student.
 In the "Courses" section, select the courses you want to enroll the student in by checkingthe
appropriate boxes.
 Click the "Save" button to create the new student.

Dept of CSE, EWIT Page 45


21CS62 | Full Stack Development

Dept of CSE, EWIT Page 46


21CS62 | Full Stack Development

Dept of CSE, EWIT Page 47

You might also like