Home > other >  How to pass parameter into the Form?
How to pass parameter into the Form?

Time:02-16

I have a form class (incorrect) :

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'}),

I want to pass parameter request.user.username.upper() which I have in my view.py. How to implement this in my TeamGoalForm?

my 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})

My Employee model:

# 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

My Department:

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()

My Managers:

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

My TeamGoal:

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()

In my app I can create Team goal for whole department or for specific group of employees.

CodePudding user response:

I would really advise not to give Manager the same name as a user and then match on that: it makes keeping records in sync quite hard. You can link to the user model with:

from django.conf import settings

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

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

you can pass the user as parameter to the ModelForm and then filter the queryset:

class TeamGoalForm(ModelForm):
    
    def __init__(self, *args, user=None, **kwargs):
        super().__init_(*args, **kwargs)
        if user is not None:
            self.field['employees'] = Employee.objects.filter(
                department__manager__user=user
            )
    
    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'})
        }

and in the view pass the logged in user to the TeamGoalForm:

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