I'm new to Django and programming. I'm trying to call the field from a model through a template other than specified in my url patterns but I keep on getting a blank display in the div block I want i to display in. I want a list of categories to be displayed in the left side-bar. I have looked at many answers on SO Django foreign key relation in template and How to display one field from a model in Django template and Ive worked through the Django docs.
I've created a list of categories in the admin class. The code is working as intended but Im not able to extend this list to be displayed from the base.html template class so that I have category navigation throughout.
I have two models:
class Post(models.Model):
category = models.ForeignKey(Categories, related_name='topic')
...
class Categories(models.Model):
topics = models.CharField(max_length=100)
...
Here is my view which works in the 'categories.html' template
def categories(request):
category = Categories.objects.all()
return render(request, 'posts/categories.html', {"category": category})
The url pattern related to it
url(r'^categories/$', views.categories, name='category'),
Here is how i'm calling the field
{% for field in category %}
<div class="col-sm-10"><a href="#">{{ field.topics }}</a></div>
{% endfor %}
I've tried alot of different approaches such as:
{% for field in category.topic.all %}
{% endfor %}
Please assist. Thank you in advance.