Search code examples
pythondjangodjango-modelsdjango-templatesone-to-one

In django how can I loop through specific fields in the parent model (user) including some specific fields in the attached child model (userprofile)


I have a table in my template, For each individual user in the User model, I want to loop through their username, phone, & email. I also want to include from the Profile model the user's age, state, & address.

my model classes in models.py:

class User(models.Model):
    ...
    username = models.CharField(max_length=100, null=True)
    phone = models.CharField(max_length=20, null=True)
    email = models.EmailField(max_length=100, blank=True, null=True)
    password = models.CharField(max_length=100, null=True)
    ...

class Profile(models.Model):
    ...
    users = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True, related_name='userprofile')
    age = models.PositiveIntegerField(blank=True, null=True)
    state = models.CharField(max_length=20, null=True)
    address = models.CharField(max_length=200, null=True)
    profile_pic = models.ImageField(upload_to='profile_pics/', null=True)
    ...

my views in views.py:

...
def registeredUsers(request):
    users = User.objects.all()
    context = {'users': users}
    return render(request, 'users.html', context)
...

My template has the table contents below:

                     ...
                        </tbody>
                            {% for i in users %}
                            <tr>
                                <td>{{ i.username }}</td>
                                <td>{{ i.phone }}</td>
                                <td>{{ i.email }}</td>
                                <td>{{ i.age}}</td>
                                <td>{{ i.state}}</td>
                                <td>{{ i.address}}</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                     ...

The template is only showing the fields in the User model, How can I define a view function to make sure that the User model pulls the fields of the Profile model with it?


Solution

  • With your models defined as they are (I'm mainly speaking about the related_name on Profile.user), write something like this inside your for loop:

    ...
    <td>{{ i.userprofile.age }}</td>
    ...