gpt4 book ai didi

python - 在模板中渲染外键列表

转载 作者:太空宇宙 更新时间:2023-11-03 20:51:13 24 4
gpt4 key购买 nike

型号

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>

网络应用程序具有登录功能。部门负责人可以签到考勤。我想在各自登录的 HOD 下呈现员工列表并标记出勤。我想在同一个 View 中执行此操作。

我无法让员工登录 HOD。

最佳答案

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

    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 %}

关于python - 在模板中渲染外键列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56304473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com