Experiment-01-08 Full Stack Django
Experiment-01-08 Full Stack Django
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.
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.
Experiment-01
Installation of Python, Django and Visual Studio code editors can be demonstrated.
Python
Here are the steps you can follow to download Python: Steps to Download & Install 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.
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.
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 ".
To verify whether the python is installed or not in our system, we have to do the following.
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 – 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.
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.
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 – 10: At this step, we have completed installing VS Code, click on Finish.
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
Experiment-02
Creation of virtual environment, Django project and App should be demonstrated.
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.
In VS Code, go to View > Terminal or use the keyboard shortcut Ctrl+`` (Windows/Linux) or
Cmd+`' (macOS) to open the integrated terminal.
In the terminal, run the following command to create a new virtual environment:
python -m venv [environment Name] OR mkvirtualenv [environment Name]
With the virtual environment active, install Django by running the following command in the
terminal: pip install django
[Replace myapp with the name you want to give to your app.]
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
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)
Once you've reviewed the migration files and are ready to apply the changes to your
database, run the following command in the terminal:
Here's how you can run the Django development server using the
python manage.py runserver command in Visual Studio Code (VS Code)
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.
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.
• 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:
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)
• 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
This maps the current_datetime view function to the root URL (/).
Output:
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.
Locate the INSTALLED_APPS list and add the name of your new app to the list:
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)
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
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
In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
Run the development server
Output:
Develop a simple Django app that displays an unordered list of fruits and ordered list of
Step-01: This app will be created in the Django project we made earlier.
Locate the INSTALLED_APPS list and add the name of your new app to the list:
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.
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">
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'),
]
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
Output:
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:
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
<footer>
<p>© {{ year }} My Website. All rights reserved. </p>
</footer>
</body>
</html>
home.html
{% extends 'layout.html' %}
{% block content %}
<h1>Welcome to My Website</h1>
{% endblock %}
Contact_us.html
{% extends 'layout.html' %}
{% block content %}
<h1>Contact Us</h1>
{% endblock %}
About_us.html
{% extends 'layout.html' %}
{% block content %}
<h1>About Us</h1>
{% endblock %}
Step-04: Create a view function
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')
In the VS Code terminal, navigate to your Django project's directory (the one containing
manage.py).
Run the development server
Output:
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.
# courses/models.py
class Student(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(unique=True)
class Course(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
students = models.ManyToManyField(Student, related_name='courses', blank=True)
Create views for registering students, enrolling in courses, and listing students in a course.
# courses/views.py
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):
courses = Course.objects.all()
return render(request, 'courses/course_list.html', {'courses': courses})
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')
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 -->
<!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
<!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>
</html>
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>
# courses/urls.py
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
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('courses.urls')),
]
Step 7: Apply Migrations
Run the migrations to create the database schema.
Output:
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.
@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
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.
Provide Superuser Information: You will be prompted to enter the following information:
Example:
Back in your web browser, enter the superuser credentials you just created and log in to
the admin interface.
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.