如何将参数传递到表单中?

How to pass parameter into the Form?

我有一个表格 class(不正确):

class TeamGoalForm(ModelForm):
    class Meta:
        employees = forms.ModelMultipleChoiceField(queryset=Employee.objects.filter(departament=Department.objects.get(manager=Manager.objects.get(end_user_id = request.user.username.upper())),widget=forms.CheckboxSelectMultiple()))
        department = forms.ModelChoiceField(queryset=Department.objects.all())
        model = TeamGoal
        fields = '__all__'
       
        widgets = {
                'employees' : forms.Select(attrs={'class': 'form-control', 'placeholder':'Select employees'}),
            }
                'department':forms.Select(attrs={'class': 'form-control', 'placeholder':'Select department'}),

我想传递 view.py 中的参数 request.user.username.upper()。如何在我的 TeamGoalForm?

中实现这个

我的view.py

@login_required(login_url='login')
def add_team_goal(request):
    form = TeamGoalForm(is_manager(request))

    if request.method == 'POST':
        form = TeamGoalForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('team_goal')

    team = get_team(request)

    if team.exists():
        return render(request, 'smth.html', {'form':form,'team':team})

我的员工模型:

# Employee section
class Employee(models.Model):
    name                = models.CharField(max_length=30, verbose_name='Name')
    lastname            = models.CharField(max_length=30, verbose_name='Lastname')
    .............
    history             = HistoricalRecords()

    
    def __str__(self):
        return self.name + ' ' + self.lastname

我的部门:

class Department(models.Model):
    id          = models.AutoField(primary_key=True)
    title       = models.CharField(max_length=30)
    .........
    manager     = models.ForeignKey(Manager, related_name='manager_name', null=True, on_delete = models.SET_NULL)
    
    history     = HistoricalRecords()

我的经理:

class Manager(models.Model):
    id          = models.AutoField(primary_key=True)
    name        = models.CharField(max_length=30)
    lastname    = models.CharField(max_length=30)
    history     = HistoricalRecords()

    def __str__(self):
        return self.name + ' ' + self.lastname

我的团队目标:

class TeamGoal(models.Model):
    team_goal_title = models.CharField(max_length=30, verbose_name='Title')
    team_goal_description = models.CharField(max_length=100, blank=True, verbose_name='Description')
    department = models.ForeignKey(Department, verbose_name='Department', on_delete = models.CASCADE, related_name='+', blank=True, null=True, help_text=u'If you assign the team goal for the whole department, please fill only Department field and skip Employee field.')
    employees  = models.ManyToManyField(Employee, null=True,  blank=True, symmetrical=False, related_name='employee_name')
    ......
    history = HistoricalRecords()

在我的应用程序中,我可以为整个部门或特定员工组创建团队目标。

我真的建议 不要Manager 一个与用户相同的名字然后匹配:这使得保持记录同步非常困难。您可以 link 到用户模型:

from django.conf import settings

class Manager(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.<strong>ForeignKey(</strong>
        <strong>settings.AUTH_USER_MODEL</strong>,
        on_delete=models.CASCADE
    <strong>)</strong>
    history = HistoricalRecords()

    def __str__(self):
        return f'{self.user.first_name} {self.user.lastname}'

您可以将用户作为参数传递给 ModelForm,然后过滤查询集:

class TeamGoalForm(ModelForm):
    
    def __init__(self, *args<strong>, user=None</strong>, **kwargs):
        super().__init_(*args, **kwargs)
        if user is not None:
            self.field['employees'] = Employee.objects.filter(
                <strong>department__manager__user=user</strong>
            )
    
    class Meta:
        model = TeamGoal
        fields = '__all__'
        widgets = {
            'employees' : forms.SelectMultiple(attrs={'class': 'form-control', 'placeholder':'Select employees'}),
            'department':forms.SelectMultiple(attrs={'class': 'form-control', 'placeholder':'Select department'})
        }

并在视图中将登录用户传递给 TeamGoalForm:

@login_required(login_url='login')
def add_team_goal(request):
    if request.method == 'POST':
        form = TeamGoalForm(request.POST<strong>, user=request.user</strong>)
        if form.is_valid():
            form.save()
            return redirect('team_goal')
    else:
        form = TeamGoalForm(<strong>user=request.user</strong>)
    team = get_team(request)
    return render(request, 'smth.html', {'form':form,'team':team})