Question

I want to iterate through User model and the UserProfile model that is attached to User to display all the information about the User in a profile page such as

UserName:
FirstName:
LastName:
Date of Birth:
.....

Is there a generic templateView, that I can use to pass the model and gets its fields displayed on template. Reading many SO articles, I tried this:

 ##display user fields
    {% for field in User._meta.get_all_field_names() %}
       <p> {{ field }} : {{ getatttr(field,user) }} </p>
     {% endfor %}
     ## display Userprofile fields
     {for field in User.profile._meta.get_all_field_names() %}
          <p> {{ field }} : {{ getatttr(field,user.profile) }} </p>
     {% endfor %}

This does not work: in fact, I tried only to display all the fields and not its values first:

{% for field in User._meta.get_all_field_names() %}
        <p> {{ field }} </p>
     {% endfor %}

but I get this error: Variables and attributes may not begin with underscores: 'User._meta.get_all_field_names'

Any idea how to fix this?

Was it helpful?

Solution

You can push this code to your view, and use the handy django.forms.models.model_to_dict function to get a dictionary of fields to values for user and user.profile

views.py:

from django.forms.models import model_to_dict

class UserDetailView(DetailView):

    model = User

    def get_context_data(self, **kwargs):
        context = super(UserDetailView, self).get_context_data(**kwargs)
        context['user_attr_map'] = model_to_dict(self.object)
        context['userprofile_attr_map'] = model_to_dict(self.object.profile)
        return context

template.html:

{% for k, v in user_attr_map.items %}
    <p> {{ k }} : {{ v }} </p>
{% endfor %}
{% for k, v in userprofile_attr_map.items %}
    <p> {{ k }} : {{ v }} </p>
{% endfor %}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top