Ad

Render A List Of Foreign Key In Template

Models

class Head_of_department(models.Model):
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    email = models.CharField(max_length=30)

    def __str__(self):
        return self.first_name 

class Employee(models.Model):
    first_name = models.CharField(max_length=200, unique=True)
    last_name = models.CharField(max_length=200, unique=True)
    head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True)
    email = models.EmailField(max_length=100)

     def __str__(self):
        return self.first_name + ' ' + self.last_name

class Attendance(models.Model):
    head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True)
    employee = models.ForeignKey('Employee', on_delete=models.CASCADE, )
    attendance = models.CharField(max_length=8, choices=attendance_choices, blank=True)

Views

class Attendancecreate(CreateView):
    model = Attendance
    fields = ['employee']
    success_url = '/dashboard/'

    def get_context_data(self,** kwargs):
        context = super(Attendancecreate, self).get_context_data(**kwargs)
        email = self.request.user.email
        hod = Head_of_department.objects.get(email=email)
        context["objects"] = self.model.objects.filter(employee__head_of_department =hod)
        print (context["objects"])
        return context

     def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.head_of_department = get_object_or_404(Head_of_department, email=self.request.user.email)
        self.object.save()
        return super().form_valid(form)

Template

<div class="form-group">
        {% for item in objects %}
            {{ item.employee }}
        {% endfor %}

</div>

The webapp has a login feature. The headofdepartment can mark the attendance . I want to render a list of employees under the respective logged in HOD and mark attendance . I want to do this in the same view .

I am unable to render the employees for logged in HOD.

Ad

Answer

I found the solution , I wrote views incorrectly.

    model = Attendance
    fields = ['employee']
    success_url = '/dashboard/'

    def get_context_data(self,** kwargs):
        context = super(Attendancecreate, self).get_context_data(**kwargs)
        email = self.request.user.email
        hod = Head_of_department.objects.get(email=email)
        context["objects"] = Employee.objects.filter(head_of_department =hod)
        print (context["objects"])
        return context

Template


{% for emp in objects %}
            {{ emp.first_name }}  {{ emp.last_name }}
 {% endfor %}
Ad
source: stackoverflow.com
Ad