I’m uisng django.contrib.auth for authentication. The User mode has a custom profile model called Personnel. Personnel is linked to another table called Company.
class Personnel(models.Model):
"""
Model for storing the personnel information
"""
user = models.OneToOneField(
User
)
company = models.ForeignKey(
Company, null=False, verbose_name="Company"
)
class Company(models.Model):
"""
Model for storing the company information.
"""
company_name = models.CharField(
null=False, max_length=200, verbose_name="Company Name"
)
-
Once the user is authenticated. How can i fetch the company for a user? Something like
request.user.... -
In the view, I can access the request but if I need to access the
requestvariable in my form and my model, do I need to pass the request variable to the form/model or is there any way to access it? This is because when I’m storing information for a particularCompany, it should be the company to which thatPersonnelbelongs to.
You should be able to access the company through
request.user.get_profile().company. See the django documentation.You cannot access
requestdirectly in a form, as the form could instantiated somewhere else too, not only in a view where norequestobject exists. You could pass the current user to the form when you initialize it (remember it makes more sense to pass the user not the request, so you can use it without a request as well).