Reputation: 2119
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)
Upvotes: 4
Views: 7159
Reputation: 2119
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 )
Upvotes: 1
Reputation: 27513
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)
Upvotes: 3