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

时间:2018-08-23 09:54:35

标签: python django admin

我正在使用请假管理系统,用户可以在其中提交此表格-

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上的文档,但无法说明问题。有人可以详细解释这个话题吗,我是否朝着正确的方向前进?

1 个答案:

答案 0 :(得分:1)

在您的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,否则,您需要从其他地方获取它们。