5 Lab Program Updated
5 Lab Program Updated
5 Lab Program Updated
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.
def __str__(self):
return self.course_name
class Student(models.Model):
student_usn = models.CharField(max_length=10)
student_name = models.CharField(max_length=100)
student_sem = models.IntegerField()
enrolment = models.ManyToManyField(Course)
def __str__(self):
return self.student_name
6. Create forms.py in course app
class CourseForm(forms.ModelForm):
class Meta:
model = Course
fields = ['course_code', 'course_name', 'course_credits']
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['student_usn', 'student_name', 'student_sem', 'enrolment']
class CourseSelectionForm(forms.Form):
course_code = forms.ModelChoiceField(queryset=Course.objects.all(),
label="Select Course")
add_course.html
<title>Add Course</title>
</head>
<body>
<h1>Add Course</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Add Course</button>
</form>
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
</body>
</html>
list_students.html
<!DOCTYPE html>
<html>
<head>
<title>List of Students</title>
</head>
<body>
<h1>Students Registered for {{ course.course_name }}</h1>
<ul>
{% for student in students %}
<li>{{ student.student_name }} ({{ student.student_usn }})</li>
{% endfor %}
</ul>
</body>
</html>
register_student.html
<!DOCTYPE html>
<html>
<head>
<title>Register Student</title>
</head>
<body>
<h1>Register Student</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
</body>
</html>
select_course.html
<!DOCTYPE html>
<html>
<head>
<title>Select Course</title>
</head>
<body>
<h1>Select Course to List Students</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Show Students</button>
</form>
</body>
</html>
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('course.urls'))
#path('', include('main.urls')),
]
13. Create database: follow below
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'pgm5',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
}
15. Run following command in VS Terminal
Output: