0

I have extended Django's user model with a Profile model:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    date_of_birth = models.DateField()
    address = models.CharField(max_length=300)
    postcode = models.CharField(max_length=15)

Then, I pass this data into a template via this view:

def profile(request):
    args = {'user': request.user}
    return render(request, 'users/profile.html', args)

Then I can access each field of the Profile model individually in the template with:

<p>Your DOB is: {{ user.profile.date_of_birth }}</p>

However, I want to use a for loop to say:

{%for field in Profile model %}
    <p>{{field name}} = {{field value}}
{% endfor %}

But I've tried a lot of different things, none of them work, e.g.

{% for field in user.profile.all %}
    <p>{{ field }}</p>
{% endfor %}

(This compiles but is blank when the template is ran)

Terminal Guy
  • 178
  • 1
  • 11
  • Possible duplicate of [Get model's fields in Django](https://stackoverflow.com/questions/3647805/get-models-fields-in-django) – dirkgroten Jan 21 '19 at 15:38
  • It doesn't "compile", template errors are usually ignored, your `Profile` objects doesn't have an attribute `all`. See the duplicate question. You won't be able to do this directly in the template, but should be able to pass the list of field names and field values in the context using the solution given. – dirkgroten Jan 21 '19 at 15:39

1 Answers1

2

Use model_to_dict to convert your instance to a python dict :

from django.forms.models import model_to_dict

def profile(request):
   profile = model_to_dict(request.user.profile)
   return render(request, 'users/profile.html', {'profile':profile})

Now you can access the fields of your profile in template :

# items is a python dictionary method to return key/value pair.
{% for field, value in profile.items %} 
    <p>{{ field }} = {{ value }}</p>
{% endfor %}
Ahtisham
  • 9,170
  • 4
  • 43
  • 57