在模板中呈现外键列表

时间:2019-05-25 11:36:50

标签: python django django-models django-templates

模型

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)

观看次数

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)

模板

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

</div>

该Web应用程序具有登录功能。部门负责人可以标记出席情况。我想在相应的已登录HOD下呈现员工列表并标记出勤。我想以相同的观点这样做。

我无法让员工登录HOD。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,我写的视图不正确。

    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

模板


{% for emp in objects %}
            {{ emp.first_name }}  {{ emp.last_name }}
 {% endfor %}