提交表单后,在 /admin 端用用户详细信息填充表单

Populate a form with the user detail after submitting the form, at /admin side

我正在开发用户提交此表单的休假管理系统 -

from django import forms
from lrequests.models import Leave

class LeaveRequestForm(forms.ModelForm): 
    class Meta:
        fields = ("department", "designation", "type_of_leave", "from_date", "to_date", "reporting_manager", "reason")
        model = Leave

其型号是-

from django.db import models
from django.contrib.auth.models import User

CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave'))
STATUS_CHOICES = ((1, 'Accepted'),(0, 'Rejected'),)
class Leave(models.Model):

    employee_ID = models.CharField(max_length = 20)
    name = models.CharField(max_length = 50)
    user = models.ForeignKey(User, on_delete = models.CASCADE, null =True)
    department = models.CharField(max_length = 50)
    designation = models.CharField(max_length = 50)
    type_of_leave = models.CharField(max_length = 15, choices = CHOICES)
    from_date = models.DateField(help_text = 'mm/dd/yy')
    to_date = models.DateField(help_text = 'mm/dd/yy')
    reporting_manager = models.CharField(max_length = 50, default = None, help_text = '0001_manager, 0002_manager')
    reason = models.CharField(max_length= 180)
    status = models.IntegerField(choices=STATUS_CHOICES, blank=True, null=True)
    reason_reject = models.CharField(('reason for rejection'),max_length=50, blank=True)

    def __str__(self):
        return self.name

用户未填写注册时提供的字段 nameemployee_ID。这些应该自动填写在管理站点和数据库中。我已经尝试并阅读了有关 ModelAdmin.prepopulated_fields 的文档,但未能切入正题。谁能详细解释一下这个话题,我的方向是否正确?

在您的 CreateView(或 FormView)中

像这样调用 get_initial()

    def get_initial(self):
        initial = super().get_initial()
        initial['name'] = self.request.user.name
        initial['employee_ID'] = self.request.user.employee_ID
        return initial

我不知道您的用户模型是否具有属性名称和员工 ID,如果没有,您需要从其他地方获取它们。