mike braa
mike braa

Reputation: 637

how to display the name field of Category model instead of [<Category: hockey>, <Category: run>]

what I'm trying to do is for sports category page display links to hockey and running category pages. I think I'm almost there, but instead of [<Category: hockey>, <Category: run>] I want hockey and run to be there.

class Category(models.Model): 
    name = models.CharField(max_length=128, unique=True) 
    parent_cat = models.ForeignKey('self', null=True, blank=True)

In template I have

<a href="/category/{{something}}">{{category.category_set.all}}</a>

my url

url(r'^category/(?P<category_name_url>[\w|\W]+)/$', views.category, name='category'),

can someone please help me out here?

Edit:My full model

class Category(models.Model): 
    name = models.CharField(max_length=128, unique=True)
    author = models.ForeignKey(settings.AUTH_USER_MODEL)
    parent_cat = models.ForeignKey('self', null=True, blank=True)
    hotCat = models.BooleanField(default=False)
    active = models.BooleanField(default=True)

    sponsored = models.ForeignKey(Sponsored, null=True, blank=True)


    objects = CategoryManager()

    def __unicode__(self): 
        return self.name

    def get_absolute_url(self):
        return "/category/%s/" %self.name

    def get_image_url(self):
        return "%s%s" %(settings.MEDIA_URL, self.image)

Upvotes: 0

Views: 33

Answers (1)

vmonteco
vmonteco

Reputation: 15423

You should use a for in loop in your template, to display the name for each category, try this :

{% for cat in category.category_set.all %}<a href="{{ cat.get_absolute_url }}">{{ cat.name }}</a> {% endfor %}

But I assumed that category.category_set.all was the way you get the set of categories to traverse. I'm not sure that this is the correct way to do this (if may be a way do to this I don't know though).

Why don't you get all categories from your view and passing the set directly as something like "categories" to your render() call?

With something like this :

def myview(request):
    cats = Category.objects.all()
    render(request, "mytemplate.html", {"categories" : cats})

Upvotes: 1

Related Questions