4

I need to get the other users of the firm within the ModelForm to set the main user, I do not know how to get variables inside the form for this?

In the view the variable needed would be:

request.user.profile.firm

This is the form that needs to be created.

class FirmForm(forms.ModelForm):

    primary = forms.ModelChoiceField(
        queryset=User.objects.filter(name=request.user.profile.firm))

    class Meta:
        model = Firm

The Profile Model:

class Profile (models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    firm = models.ForeignKey(
        Firm, on_delete=models.CASCADE, null=True, blank=True)


    def __str__(self):
        return str(self.user.username)

The Firm model

class Firm (models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return str(self.name)
Brown Bear
  • 19,655
  • 10
  • 58
  • 76
diogenes
  • 1,865
  • 3
  • 24
  • 51

2 Answers2

4
primary = forms.ModelChoiceField(
        queryset=User.objects.filter(name=request.user.profile.firm.name))

use this in your model form

in views where you are accessing the Form

FirmForm(request=request)
Exprator
  • 26,992
  • 6
  • 47
  • 59
1

I got this to work. the best I could do. Thanks.

def __init__ ( self,  *args, **kwargs ):
    super ( FirmForm, self ).__init__ ( *args, **kwargs )
    instance = getattr ( self, 'instance', None )
    firm = self.instance
    self.fields [ 'contact' ].queryset = Profile.objects.filter ( firm = firm )
diogenes
  • 1,865
  • 3
  • 24
  • 51