Class Based View
Class Based View
class Department(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Employee(models.Model):
name = models.CharField(max_length=200,)
designation = models.CharField(max_length=200,)
email=models.EmailField(blank=True)
joining_date = models.DateField(auto_now_add=True)
salary = models.FloatField(blank=True, null=True,validators=[MinValueValidator(20000),
MaxValueValidator(10000000)])
department = models.ForeignKey(Department, blank=True, null=True,on_delete=models.CASCADE)
def __str__(self):
return self.name
13. In day3Apps/views.py, enter the following code:
class EmployeeBaseView(View):
model = Employee
fields = '__all__'
success_url = reverse_lazy('day3App:all')
app_name = 'day3App'
urlpatterns = [
path('', views.EmployeeListView.as_view(), name='all'),
path('<int:pk>/detail', views.EmployeeDetailView.as_view(), name='employee_detail'),
path('create/', views.EmployeeCreateView.as_view(), name='employee_create'),
path('<int:pk>/update/', views.EmployeeUpdateView.as_view(), name='employee_update'),
path('<int:pk>/delete/', views.EmployeeDeleteView.as_view(), name='employee_delete'),
]
15. Adding the Templates
After defining the CRUD views, you next need to add the template for each of your views. Each
view expects a template with a specific name in the templates folder of your application.
a) Inside the templates folder, create a templates/day3App/ folder and start by adding
the employee_list.html file with the following content:
<h1>Employee List</h1>
<hr>
<table>
<thead>
<tr>
<th>Name</th>
<th>Designation</th>
<th>Email</th>
<th>Joining Date</th>
<th>Salary</th>
<th>Department</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<hr>
<a href="{% url 'day3App:employee_create' %}" >Add New Employee</a>
</form>
<h1>Employee Details</h1>
<hr>
<p>Name: {{employee.designation}}</p>
<p>Designation: {{employee.designation}}</p>
<p>Email Address: {{employee.email}}</p>
<p>Joining Date: {{employee.joining_date}}</p>
<p>Salary: {{employee.salary | floatformat:2}}</p>
<p>Department: {{employee.department}}</p>
<hr>