Django:自动填充其他模型的外键表单字段

时间:2018-10-01 14:28:29

标签: django django-models django-forms django-views

目前,我正在建立一个门户网站来跟踪员工信息。我现在在此缺席系统上添加日志以记录他们并跟踪他们累积的出勤点。旷工模型链接到Employee模型,如下所示:

class Absentee(models.Model):
    employee = models.ForeignKey(Employee, null=True, on_delete=models.CASCADE, related_name="absentee_employee")
    date = models.DateField(null=False, blank=False)
    reason = models.ForeignKey(Absence, null=True, on_delete=models.CASCADE, related_name="absentee_reason")
    added_by = models.ForeignKey(Supervisor, null=True, on_delete=models.SET_NULL, related_name="absentee_supervisor")
    comment = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        ordering = ('date', )

    def __str__(self):
        return f"{self.employee.CoreID} [{self.reason.points}] - {self.comment}"

当您转到员工模型所引用的单个员工的详细信息页面时,我设法能够将缺席者显示为表格。在此员工详细信息页面中,有一个按钮,用于添加一个缺勤者,该缺勤者将以引用缺勤者模型的形式创建一个新的缺勤者。但是,问题在于我无法根据用户在转到表单之前正在寻找的雇员来自动填充外键字段“雇员”。有没有办法自动完成此字段?以下是网址和视图:

urls.py:

    path('employees/<int:pk>/', views.ManpowerDetailView.as_view(), name='manpower_detail'),
    path('employees/<int:pk>/absentee/new/', views.AbsenteeCreateView.as_view(), name='absentee_new'),

views.py:

    class ManpowerDetailView(GroupRequiredMixin, DetailView):
        model = models.Employee
        template_name = 'manpower/manpower_detail.html'
        group_required = ['Supervisor', 'Manager', 'Admin']

    class AbsenteeCreateView(GroupRequiredMixin, CreateView):
        model = models.Absentee
        template_name = 'manpower/absentee_new.html'
        fields = ['employee', 'date', 'added_by', 'reason', 'comment', ]
        group_required = ['Supervisor', 'Manager', 'Admin']
        success_url = reverse_lazy('manpower_list')

0 个答案:

没有答案