I am working on a page to display a users profile. I have successfully rendered an instance of the users profile, which looks as shown in the screenshot below. The thing I want to change, is to display the verbose name of the field names, rather than the actual field name. I have done some research but am not sure how to implement this with my current set up.
My models.py:
class Profile(models.Model):
MALE = 'M'
FEMALE = 'F'
OTHER = 'O'
UNSPECIFIED = "U"
GENDER_CHOICES = [
(MALE, 'Male'),
(FEMALE, 'Female'),
(OTHER, 'Other'),
(UNSPECIFIED, 'Prefer not to say'),
]
user = models.OneToOneField(User, on_delete=models.CASCADE)
phone_number = models.CharField(verbose_name='Mobile Phone Number', max_length=20)
bio = models.TextField(verbose_name='Bio', max_length=500, blank=True, null=True)
date_of_birth = models.DateField(verbose_name='Date of Birth', blank=True, null=True)
first_name = models.CharField(verbose_name='First Name', max_length=255, blank=True, null=True)
surname = models.CharField(verbose_name='Surname', max_length=255, blank=True, null=True)
gender = models.CharField(verbose_name='Gender', max_length=255, choices=GENDER_CHOICES, blank=True, null=True)
emergency_contact_name = models.CharField(verbose_name='Emergency Contact Name', max_length=255, blank=True, null=True)
emergency_contact_number = models.CharField(verbose_name='Emergency Contact Number', max_length=20, blank=True, null=True)
business = models.ForeignKey(BusinessProfile, null=True, blank=True, on_delete=models.SET_NULL)
creation_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.user)
Views.py:
class ShowProfileView(DetailView):
model = Profile
template_name = 'profiles/user_profile.html'
def get_context_data(self, *args, **kwargs):
context = super(ShowProfileView, self).get_context_data(*args, **kwargs) # super gives access to parent class methods
user_profile = get_object_or_404(Profile, id=self.kwargs['pk']) # 'id' is representative of the <int:pk> tag in the url. This means could change 'pk' to be 'id' in both view and url files, and it would still work. So within the url 'pk' is the dictionary key,
# and the actual value which is passed into the url (that you see in the search bar) is the dictionary value.
context["user_profile"] = user_profile
return context
def get_object(self, *args, **kwargs):
obj = Profile.objects.filter(id=self.kwargs['pk']).values('first_name', 'surname', 'date_of_birth', 'phone_number', 'bio', 'date_of_birth', 'gender', 'emergency_contact_name', 'emergency_contact_number') # list of dictionaries
object = obj[0]
return object
user_profile.html:
{% extends "base.html" %}
{% block content %}
<h1>Profile</h1>
<br/><br/>
{% csrf_token %}
<ul>
{% for k, v in object.items %}
<p>{{ k }}: {{ v }}
{% endfor %}
</ul>
<a href='{% url "profiles:edit_profile" pk=user.profile.id %}'>Edit Profile</a>
{% endblock %}
And a screenshot of how this looks:
Any help much appreciated! Thanks.