Filter users by group in form calss

Hi, I want to save data about users in tables as presented below:
Models.py

class Operation_count(models.Model):
    EventID    = models.PositiveIntegerField()
    ModelID    = models.CharField(max_length=50)
    Workers    = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='Workers_event',on_delete=models.CASCADE)
    post_date  = models.DateTimeField(auto_now_add=True)
    author     = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='create_posts',on_delete=models.CASCADE)
    def __str__(self):
        return self.EventID
    def get_absolute_url(self):
        return reverse('WellNetwork')
    class Meta:
        ordering = ('-post_date',)

and the issue is in the Workers field so I have many users then I need to filter them according to the current user group and their group, this is the form I use:

class Operation_count_F(forms.ModelForm):
    EventID  =  forms.IntegerField(required=False)    
    ModelID  =  forms.CharField(required=False)
    Workers  =  forms.ModelChoiceField(label='Co-Worker', queryset=User.objects.all())
    class Meta:
        model= Operation_count
        fields=('EventID','ModelID','Workers')

So here I can’t call the current user and its group and then filter all users that belongs to the same user.
How I do to solve this?
I use a function by the way in views.py

def post_EvWorks(request, Evt_id): 
    form = Operation_count_F()
    if request.method == 'POST':
            pass
    elif request.POST.get("form_Glift") == "Save Parameters":
            print("Save Parameters")
            form =form(request.POST)
            if form.is_valid():
                form.instance.author = request.user
                form.save()
                return redirect('Events', Evt_id)
            else:
                form_errorGL = 'Check your file Name'

You’ve got a couple different options:

  • You can modify the form to accept parameters, pass the parameter in through the constructor call, and use that parameter in the form to modify the form field.

  • Modify the form field directly after the form has been constructed, in the view.

1 Like

Many thanks, but your answers are getting hard to understand and need to post them as a question in other topics.

think this site is for experts only and I need to find another place to post questions.

All my best

Or, you could ask for further clarification if necessary. You’ve been an active member here for more than 4 months now - it’s tough to judge just how far you’ve come and what level of detail is necessary for any particular question you may ask.

1 Like

Hi, many thanks,

this solution workes for me, I just filtered the users in the views.py before passed to form.py as:

def post_EvWorks(request, Evt_id):
    All_group = request.user.groups.all()
    theGroup= All_group.exclude(name='Service_head')
    theGroup= theGroup.exclude(name='Admin_stuff').first()
    print(request.user, 'post_EvWorks3', theGroup )
    form = Operation_count_F()
    form.fields['Workers'].queryset = User.objects.filter(groups__name=theGroup)
    if request.method == 'POST':
        if request.POST.get("form_uplod") == "Add file":
            pass
        elif request.POST.get("form_Glift") == "Save Parameters":
            print("Save Parameters")
            form =form(request.POST)
            if form.is_valid():
                form.instance.author = request.user
                form.save()
                return redirect('Events', Evt_id)
            else:
                form_errorGL = 'Check your Name'

so key is in this line

   form.fields['Workers'].queryset = User.objects.filter(groups__name=theGroup)

many thanks