Im using the below code in my views.py page to render a html page. This piece of code is from a Django book and im trying to understand the bookmark_set attribute.
views.py
def user_page(request, username):
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
raise Http404(u'Requested user not found')
bookmarks = user.bookmark_set.all()
template = get_template('user_page.html')
variables = Context({'username':username, 'bookmarks':bookmarks})
output = template.render(variables)
return HttpResponse(output)
models.py
from django.db import models
from django.contrib.auth.models import User
class Link(models.Model):
url = models.URLField(unique=True)
class Bookmark(models.Model):
title = models.CharField(max_length=200)
user = models.ForeignKey(User)
link = models.ForeignKey(Link)
When I run this piece of code in my Python shell, I get the following error
from django.contrib.auth.models import User
from bookmarks.models import *
user=User.object.get(id=1)
user.bookmark_set.all()
Attribute Error: ‘User’ object has no attribute ‘bookmark_set’
Why do I get this error?
How does the set attribute of the User work?
The
bookmark_setattribute provides a convenient way to traverse the reverse relationship, i.e. to get all of a user’s bookmarks. You can read more about it in the docs:You can actually specify the name of the reverse relationship attribute by providing a
related_namein your model:Have you definitely created your models in the DB by running
python manage.py syncdb? It looks like you are doing everything correctly