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

FSD-module-2 Lab Programs

Uploaded by

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

FSD-module-2 Lab Programs

Uploaded by

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

DEPT.

OF AIML, JNNCE, SHIVAMOGGA

SUBJECT: FULLSTACK DEVELOPMENT (21CS62)

LAB COMPONENT SOLUTIONS

Module-2: Django Templates and Models

Sample program:
Views.py in app1
from django.template import loader
from django.shortcuts import render
from django.http import HttpResponse
def members(request):
template=loader.get_template('template.html')
context={'myname':'SJCIT'}
return HttpResponse(template.render(context,request))

Template.html
<!DOCTYPE html>
<html>
<body>
<h1>Hello {{myname}},wellcome to trainig</h1>
</body>
</html>

Urls.py in proj
from django.contrib import admin
from django.urls import path,include

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

Urls.py in app1
from django.urls import path

10 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

from . import views

urlpatterns = [
# path('admin/', admin.site.urls),
path('members/',views.members,name='members')

settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1' ,
]

Output

2)Views.py
from django.template import loader
from django.shortcuts import render
from django.http import HttpResponse
def members(request):
template=loader.get_template('templates.html')
context={'greeting' : 1,}
return HttpResponse(template.render(context,request))
URLS.py

from ap1 import views


urlpatterns = [
path('admin/', admin.site.urls),
path('members/',views.members,name='members'),
]
Templates.html
<!DOCTYPE html>

10 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

<html>
<body>
<p>you belong to the department</p>
{% if greeting == 1 %}
<h1>CSE</h1>
{% else %}
<h1>ISE</h1>
{% endif %}
</body>
</html>

output

3) Views.py
from django.template import loader
from django.shortcuts import render
from django.http import HttpResponse
def members(request):
template=loader.get_template('templates.html')
context={'fruits':['Apple ','Banana','mango'] }
return HttpResponse(template.render(context,request))
URLS.py

from ap1 import views


urlpatterns = [
path('admin/', admin.site.urls),
path('members/',views.members,name='members'),
]
Templates.html
<!DOCTYPE html>
<html>
<body>
<p>FRUITS</p>
{% for x in fruits %}
<h1>{{x}}</h1>
{% endfor %}
</body>
</html>

output
10 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

Template example program:


Views.py
from datetime import date
from django.http import HttpResponse
from django.shortcuts import render
from django.template import Context, Template

def template_test(request):
t=Template("""
<html>
<body>
{% if attending %}
<h1>Welcome {{ participant.name|upper }},{{
participant.dept}} to FDP {{ fdp_name }}
on {{ fdpdate|date:"F j,Y"}} </h1>
{% if atd_per > 80 %}
<h2> Very Good </h2>
{% elif atd_per > 60 %}
<h2> Good </h2>
{% else %}
<h2> Not satisfactory </h2>
{% endif %}
Your phone no is {{ participant.pno}}
<h1>List of Topics</h1>
<ul>
{% for topic in topics %}
10 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

<li>{{ forloop.revcounter0}}: {{ topic }}</li>


{% endfor %}
{% else %}
<h1>Thank you </h1>
{% endif %}

</body>
</html>
""")
fdp_name="Programming with Julia"
atd_per=66
participant={"name":"Chetan","pno":"9900923050","dept":"AIML"}
topics=["Models","Views","Templates","AJAX","NonHTML"]
c=Context({"fdp_name":
fdp_name,"topics":topics,"participant":participant,"attending":True,"atd_per":
atd_per,"fdpdate":date(2024,4,9)})
return HttpResponse(t.render(c))

URLS.py
from django.contrib import admin
from django.urls import path, re_path
from ap2.views import create_table_of_squares,vc,find_mode
from ap2.views import template_test

urlpatterns = [
path('admin/', admin.site.urls),
path('vc/<str:sentence>', vc),
path('find_mode/<str:listofnum>', find_mode),
path('template_test/', template_test),

Output:

10 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

Develop a Django app that displays list of subject codes and subject names of any
semester in tabular format. Even rows should have a light green background color
and subject names should be in all caps

Views.py in app2

from django.http import HttpResponse


from django.shortcuts import render
from django.template import Context, Template

def list_of_subjects(request):
s1={"scode":"21CS51","sname":"cn"}
s2={"scode":"21CS52","sname":"ATc"}
s3={"scode":"21CS53","sname":"DbMS"}
s4={"scode":"21AI54","sname":"PAI"}
l=list()
l=[s1,s2,s3,s4]
return render(request,'list_of_subjects.html',{"l":l})

URLS.py in app2
from django.urls import path

from . import views

urlpatterns = [
# path('admin/', admin.site.urls),
path('LOS/',views.list_of_subjects,name='list_of_subjects')

]
URLS.py in proj
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
path('admin/', admin.site.urls),
path('',include('app1.urls')),
path('',include('app2.urls')),

Template file: list_of_subjects.html

<html>
<body>
<table border>
<tr>
10 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

<th>Subject Code</th>
<th>Subject Name</th>
</tr>
{% for subject in l %}
{% if forloop.counter|divisibleby:"2" %}
<tr>
<td style="background-color: lightgreen;">{{ subject.scode }}</td>
<td style="background-color: lightgreen;">{{
subject.sname|upper}}</td>
</tr>
{% else %}
<tr>
<td>{{ subject.scode }}</td>
<td>{{ subject.sname|upper }}</td>
</tr>
{% endif %}
{% endfor %}
</table>
</body>
</html>
Setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1' ,
'app2' ,
]

Output:

10 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

Module-2 Laboratory Component:


1. Develop a simple Django app that displays an unordered list of fruits
and ordered list of selected students for an event

Views.py in members
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader

def showlist(request):
template = loader.get_template('showlist.html')
fruits=["Mango","Apple","Bananan","Jackfruits"]
student_names=["Tony","Mony","Sony","Bob"]
return
render(request,'showlist.html',{"fruits":fruits,"student_names":student_names}
)

URLS.py in app name members


from django.urls import path
from . import views

urlpatterns = [
path('showlist/', views.showlist, name='showlist'),

URLS.py in project name store


from django.contrib import admin
from django.urls import path , include

from members.views import showlist

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

Template HTML file (inside members/templates subfolder)


showlist.html
<html>
<style type="text/css">
#i1 {background-color: lightgreen;color:brown;display:table}
#i2 {background-color: black;color:yellow}
</style>
<body>

10 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

<h1 id="i1">Unordered list of fruits</h1>


<ul>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</ul>
<h1 id="i2">Ordered list of Students</h1>
<ol>
{% for student in student_names %}
<li>{{ student }}</li>
{% endfor %}
</ol>
</body>
</html>
Setting.py( make sure that ur app name should be added to installed app)
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'members'
]

Output:

10 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

2. 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 additional pages: contact us, About Us and
Home page of any website.

Views.py in app3
from django.http import HttpResponse
from django.shortcuts import render
from django.template import Context, Template
def home(request):
return render(request,'home.html')

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

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

URLS.py in app3
from django.urls import path

from . import views

urlpatterns = [
# path('admin/', admin.site.urls),
#path('LOS/',views.list_of_subjects,name='list_of_subjects')
path('aboutus/', views.aboutus,name='aboutus'),
path('home/', views.home,name='home'),
path('contactus/',views.contactus,name='contactu'),

10 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

Template files:
layout.html
<html>
<title>{% block title %} {% endblock %} </title>
<style type="text/css">
nav {background-color: lightblue;padding:10px}
</style>
<body>
<nav>
<a href="/home/">Home</a>|
<a href="/aboutus/">About Us</a>|
<a href="/contactus/">Contact Us</a>|
</nav>
<section>
{% block content %}{% endblock %}
</section>
<footer>
<hr>
&copy; ISE, Developed by ABC, Inc.
</footer>
</body>
</html>

home.html

{% extends 'layout.html' %}
{% block title %} Home
{% endblock %}
{% block content %}
<h2>This is the home page</h2>
{% endblock %}

11 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

aboutus.html
{% extends 'layout.html' %}
{% block title %} About Us
{% endblock %}
{% block content %}
<h2>We are DJango developers</h2>
{% endblock %}

contactus.html
{% extends 'layout.html' %}
{% block title %} Contact us
{% endblock %}
{% block content %}
<h2>Out phone: 8147235567 <br> Address: Ram SJCIT</h2>
{% endblock %}

Setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1' ,
'app2' ,
'app3' ,

Output:

12 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

3. 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
ManyToMany field.

course_search.html file in templates folder

<html>
<body>
<form method="POST" action="">
Courses
{% csrf_token %}
<select name="cname">
{%for course in courses %}
<option value="{{course.id}}">{{course.course_name}}</option>
{% endfor %}
</select>
<input type="submit" value="Search">
</form>
</body>
</html>

selected_students.html

<html>
<body>
<table border>
<tr>
<th>Student Name</th>
<th>Student USN</th>
<th>Sem</th>
</tr>
{% for student in student_list %}
<tr>
<td>{{student.student_name}}</td>
<td>{{student.student_usn}}</td>
<td>{{student.student_sem}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>

13 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

reg.html

<html>
<body>
<form method="post" action="">
{% csrf_token %}
Student Name
<select name="sname">
{%for student in students %}
<option value="{{student.id}}">{{student.student_name}}</option>
{% endfor %}
</select><br>
Course Name
<select name="cname">
{%for course in courses %}
<option value="{{course.id}}">{{course.course_name}}</option>
{% endfor %}

</select><br>
<input type="submit" value="Enroll">
</form>
</body>
</html>

Views.py

from django.http import HttpResponse


from django.shortcuts import render

from ap1.models import Course, Meeting, ProjectReg, Student

def reg(request):
if request.method == "POST":
sid=request.POST.get("sname")
cid=request.POST.get("cname")
student=Student.objects.get(id=sid)
course=Course.objects.get(id=cid)
res=student.enrolment.filter(id=cid)
if res:
return HttpResponse("<h1>Student already enrolled</h1>")
student.enrolment.add(course)
return HttpResponse("<h1>Student enrolled successfully</h1>")

else:
students=Student.objects.all()
courses=Course.objects.all()
return render(request,"reg.html",{"students":students,
"courses":courses})
14 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

def course_search(request):
if request.method=="POST":
cid=request.POST.get("cname")
s=Student.objects.all()
student_list=list()
for student in s:
if student.enrolment.filter(id=cid):
student_list.append(student)
if len(student_list)==0:
return HttpResponse("<h1>No Students enrolled</h1>")
return
render(request,"selected_students.html",{"student_list":student_list})

else:
courses=Course.objects.all()
return render(request,"course_search.html",{"courses":courses})

models.py
from django.db import models
from django.forms import ModelForm

# Create your models here.


class Meeting(models.Model):
meeting_code=models.CharField(max_length=100)
meeting_dt=models.DateField(auto_now_add=True)
meeting_subject=models.CharField(max_length=100)
meeting_np=models.IntegerField()

class Course(models.Model):
course_code=models.CharField(max_length=40)
course_name=models.CharField(max_length=100)
course_credits=models.IntegerField()
def __str__(self):
return self.course_name

class Student(models.Model):
student_usn=models.CharField(max_length=20)
student_name=models.CharField(max_length=100)
student_sem=models.IntegerField()
enrolment=models.ManyToManyField(Course)
def __str__(self):
return self.student_name+"("+self.student_usn+")"

15 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

urls.py

from django.contrib import admin


from django.urls import path, re_path

from ap1.views import reg, course_search


admin.site.site_header="My Site Header"
admin.site.site_title="My Site Title"
admin.site.index_title="My Site Index"
urlpatterns = [
path('admin/', admin.site.urls),
path('reg/', reg),
path('course_search/', course_search)
]

Output:

Perform migrations before running:

 python manage.py makemigrations

 python manage.py migrate

Database input:
Insert student and courses record in db.sqlite3 or
PhPmyadmin

16 | P a g e
DEPT. OF AIML, JNNCE, SHIVAMOGGA

Back End

17 | P a g e

You might also like