Ok so I'm new to Django (and programming in general and I'm building a website that requires multiple types of users. I created a base class that I have in AUTH_PROFILE_MODULE and have the different user types inheriting from the base class. My question is how can I access the data saved from the the classes inheriting from the base class in my templates. I know I can use user.get_profile.field for anything I have within the base class, but it doesn't work for the fields I have outside of the base class. It might be easier to understand if you can see my code...
models.py
class BaseProfile(models.Model):
user = models.ForeignKey(User, unique=True)
#Other common fields
...
class StudentProfile(BaseProfile):
user_type = models.CharField(max_length=20, default="student")
#Other student specific fields
...
class InstructorProfile(BaseProfile):
user_type = models.CharField(max_length=20, default="instructor")
#Other instructor specific fields
...
settings.py
AUTH_PROFILE_MODULE = 'signup.BaseProfile'
I have separate forms for instructors and students and have user_type as a HiddenInput field in each so it cannot be changed by the user so it defaults to what I want it to. I also set my signal to accommodate the different form information that I need. I can see in the admin that my signal will successfully save user_type as "instructor" or "student" respectively depending on which form is used, but I don't know how to retrieve that in my template. I have tried several variations including:
template.html
{% if user.get_profile.user_type == "instructor" %}
{% if user.user_type == "instructor" %}
{% if user.InstructorProfile.user_type == "instructor" %}
Again I'm very new to programming in general, not just Python, so please forgive me if I didn't provide enough information or explain clearly. Thanks in advance for any help. Let me know if I need to provide any other information. I am unable to find the answer through a search.
The first variation would be the right one, but the problem is that your user_type field is on the subclass, not the base class. When you do get_profile
, you only get the base class, as Django has no way of knowing simply from the database what sort of subclass you are expecting.
Rather than putting the user_type field on the subclass and setting a default, put it in the base class, and override your save
method to set it appropriately.