Ahmed Wagdi
Ahmed Wagdi

Reputation: 4391

Getting the pk from url in Django

here is my URL structure that I use to get the item pk in the link :

urls.py

path('categories/<int:item_category>/', views.item_category, name="item_category"),

views.py

def item_category(request, pk):
    item_category = get_object_or_404(Categories, pk=pk)
    ids = [self.kwargs.get('pk')]
    cat_id = Categories.objects.get(pk=ids)

    return render(request, 'items_modal.html', {'item_category': item_category,
                                                'cat_id': cat_id
                                                })

Now I want to use the pk to get the result on the new link here is my HTML

  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">{{ cat_id }}</h5>

Upvotes: 1

Views: 5891

Answers (2)

HenryM
HenryM

Reputation: 5793

I think you have a couple of errors.

  1. change the url:

    path('categories/<int:pk>/', views.item_category, name="item_category"),

  2. Your function is confusing. You do not want a variable with the same name as a function which is getting you object and cat_id is an object and not an integer

    def item_category(request, pk): cat = get_object_or_404(Categories, pk= return render(request, 'items_modal.html', {'item_category': cat})

  3. Displaying the id:

    <h5 class="modal-title" id="exampleModalLabel">< ahref="{% url 'item_category' item_category.id %}">{{ item_category }}</a></h5>

Upvotes: 4

aman kumar
aman kumar

Reputation: 3156

change the keyword in url

path('categories/<int:pk>/', views.item_category, name="item_category"),

Upvotes: 0

Related Questions