Friday, 23 August 2013

Trying to select by field from different class using foreign key, getting errors

Trying to select by field from different class using foreign key, getting
errors

I'm creating a reddit clone as a personal project to get to grips with
django, and so far I've got two classes:
from django.db import models
from django.contrib.auth.models import User
class Board(models.Model):
name = models.CharField(max_length =100, blank = False)
created_on = models.DateTimeField('Date Created', auto_now_add=True)
deleted = models.BooleanField(default = False)
def __unicode__(self):
return self.name
class Notice(models.Model):
title = models.CharField(max_length=200) #title as it appears on the
notice
author = models.ForeignKey(User, null=False, blank=False)
posted_on = models.DateTimeField('Posted On', auto_now_add= True)
updated_on = models.DateTimeField('Last Updated', auto_now = True)
board = models.ForeignKey(Board, null=False)
isText = models.BooleanField(null=False, blank = False)
content = models.TextField()
thumps_up = models.PositiveIntegerField()
thumps_down = models.PositiveIntegerField()
deleted = models.BooleanField(default=False)
def __unicode__(self):
return self.title
And in my urls I have:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<board_name>\w+)/$', views.board_lv)
)
What I want to do is have the url pattern compare against the "name" field
in the "Board" model using the "board" foreign key in the "Notice" model,
and then open up a page listing all the notices with in that board
(similar to subreddits in reddit).
I'm getting a type error saying "Notice object is not iterable", which
leads me to think I've only got one object instead of a list, but I
shouldn't have should I?
The iteration is in this part of the html file;
{% for n in latest_notices %}
<li>
{% if not n.isText %}
<h2><a href="{{ n.content }}">{{ n.title }}</a></h2>
{% else %}
<h2>{{ n.title }}</h2>
<p>{{ n.content }}</p>
{% endif %}
</li>
{% endfor %}
where the views are:
def index(request):
latest_notices = Notice.objects.order_by('-posted_on')
context = {'latest_notices': latest_notices}
return render(request, 'noticeList.html', context)
def board_lv(request, board_name):
latest_notices = get_object_or_404(Notice, board__name=board_name)
context = {'latest_notices': latest_notices}
return render(request, 'noticeList.html', context)
Also, in the error traceback, the board_name variable value is preceded by
a 'u' before the quoted string, e.g:
Variable Value
board_name u'worldnews'
If I'm getting the url pattern wrong or haven't explained the problem well
enough, please let me know as any help would be greatly appreciated.

No comments:

Post a Comment