Answer the question
In order to leave comments, you need to log in
How to get pk from request in Django?
Good afternoon. Stupid noob question.
There is a model:
class News(models.Model):
....
category = models.ForeignKey(Category,null=True,on_delete=models.SET_NULL)
class Category(models.Model):
cat_name = models.CharField(max_length=50, unique=True)
url(r'^category/(?P\d+)/$', views.category, name='category'),
def category(request,pk):
latest_news_category_list = News.objects.filter(category_id=pk).order_by('-pub_date')
context = {'latest_news_category_list': latest_news_category_list}
return render(request, 'news/detail.html', context)
<p>Категория:<a href="{% url 'news:category' news.category.id %}"> {{ news.category }}</a></p>
Answer the question
In order to leave comments, you need to log in
url(r'^category/(?P<category_id>\d+)/$', views.category, name='category'),
# view
def category(request, category_id):
latest_news_category_list = News.objects.filter(category=category_id).order_by('-pub_date') # <<
context = {
'latest_news_category_list': latest_news_category_list,
'category': get_object_or_404(Category, id=category_id)} #<< 404 если ид нет в бд
return render(request, 'news/detail.html', context)
# tpl
{% for news_item in latest_news_category_list %}
<p>Категория:
<a href="{% url 'news:category' category_id=news_item.id %}">
{{ news_item.category.cat_name }} тайтл новости</a></p>
{% endfor %}
но лучше добавить в контекст отдельно категорию
<p>Категория:
<a href="{% url 'news:category' category_id=category.id %}">
{{ category.cat_name }}</a></p>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question