ryan
ryan

Reputation: 645

How to use models associated with a user in Django when rendering an HTML page

I'm in the learning stages of django. I just dived into a project to learn the framework and am having a series of questions throughout the process.

I basically want to have individual pages for users who create a task list and have them post tasks to their own page.

from django.db import models from django.contrib.auth.models import User

# Create your models here.
class UserProfile(models.Model):
    # This line is required. Links UserProfile to a User model instance.
    user = models.OneToOneField(User)
    # The additional attributes we wish to include.
    website = models.URLField(blank = True)
    # Override the __unicode__() method to return out something meaningful!
    def __unicode__(self):
        return self.user.username

class TaskItem(models.Model):
    taskn = models.CharField(max_length = 400)
    usern = models.ForeignKey(User)

In my template, if the user has their task entered, how do I call it to render onto the page?

My View:

def profile_page(request, username):
    user = User.objects.get(username=username)
    taskitems = user.taskn_set.all()
    return render_to_response('profile.html', {}, context)

Current issue:

'User' object has no attribute 'taskn_set'

Upvotes: 0

Views: 182

Answers (2)

HassenPy
HassenPy

Reputation: 2103

you would do something like this:

{% for task in user.taskitem_set.all %}
    {{ task.task_n }}
{% endfor %}

This will fetch all TaskItem instances related to your user. (notice the extra database query)

While i don't know how your view works, i will assume that you are making the right checks to make sure that every user can only see his own tasks.

One performance trick you will find most useful is to use prefetch_related('taskitem_set'), this will prefetch the TaskItem instances as long as your UserProfile instance with one query:

user = User.objects.filter(id=user_id).prefetch_related('taskitem_set')

You can tune the code to match your preferences.

Hope this helps!

Upvotes: 0

karthikr
karthikr

Reputation: 99660

{{ request.user.taskitem_set.all }} would give you all the related task items. Now, to display it in your template:

{% for task_item in user.taskitem_set.all %}
    {{ task_item.task_n }}
{% endfor %}

would display the list of tasks.

Here is the documentation on reverse-queries on foreign key (related_name) Also, read this

Upvotes: 1

Related Questions