Z
Z
zigen2015-04-06 12:10:56
Django
zigen, 2015-04-06 12:10:56

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)

I want to receive all the news related to this category. But I can't figure out how to get pk from a request.
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)

Sample:
<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

1 answer(s)
S
sim3x, 2015-04-06
@zigen

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>

localhost:8000/news/category/1
Do not use reserved variable names like pk, id without understanding what you are doing

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question