Question

i have 2 tables, WorkingHours and Employee, in Employee i define workingHours = models.ManyToManyField(WorkingHours). My Employee and WorkingHours have a foreign key to User.

Now i have some form for adding a WorkingHour (under some user) and i want to add on existing form that user can multiple choose between his Employees.

So i have existing form, that user can add WorkingHours, now i want to add a option that he can choose between his Employees. Now is realised only adding WorkingHours for some User, i want add a option to choose between his Employees, and i don't have any ideas how to do this.

So, for better understanding, i have user, who have WorkingHours and i want to add that user can choose which Employee "works" on this WorkingHours. If all fields be unchecked, i want to apply to all Employees that WorkingHour

I hope its not too complicated, if it is i will try to explain more in comments.

I am working on existing project, so i don't want to change a lot of code.

Thanx

Was it helpful?

Solution

I think I understand the basic problem. You need a Multiple choice field which is populated with the employees associated with that user.

Look here for some details/examples.

Basically you want something like this, this example doesn't do everything but I hope it's a start.

class SimpleForm(forms.Form):
    employees = forms.MultipleChoiceField(required = False, widget=forms.SelectMultiple)

def __init__(self, *args, **kw)
    user = kw.pop('user') # you need to pass user to into this function as a kw argument
    super(SimpleForm, self).__init__(*args, **kw)
    # this asssumes the user as a field (or related field reference) to employees
    # either way somehow you need to execute a query which gets the users employees.
    self.fields['employees'].choices = user.employees.all()

def save(self, *args):
    # if employees is empty set them all to selected
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top