Home > Net >  How do you pass two parameters through url in django
How do you pass two parameters through url in django

Time:12-27

I want to pass two parameters through url in django. First of all, here is my current html:

{% for lesson in lessons %}
{% for class in lessons %}
    <a href="{% url 'next-page' lesson.pk %}">Link to next page {{lesson}} {{class}}</a>
{% endfor %}
{% endfor %}

And this is my url:

path('nextpage/<int:pk>/', ListView.as_view(), name='next-page'),

However, I want something like below:

{% for lesson in lessons %}
{% for class in lessons %}
    <a href="{% url 'next-page' lesson.pk class.pk %}">Link to next page {{lesson}} {{class}}</a>
{% endfor %}
{% endfor %}

and my url is:

path('nextpage/<int1:pk>/<int2:pk>', ListView.as_view(), name='next-page'),

Then I want to be able to access the primary keys in my view below:

class LessonList(generic.ListView):
    model = Lesson
    template_name = 'lesson_list.html'
    context_object_name = "lessons"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        lesson_id = self.kwargs['pk1']
        class_id = self.kwargs['pk2']

        return context

Obviously, the above code does not work. However, I want to basically be able to pass two parameters in the url, and access both of them in my view's get_context_data. Thank you, and please leave any questions you might have.

CodePudding user response:

You made a mistake when defining your path, it should be <int:pk1> instead of <int1:pk>, so:

path('nextpage/<int:pk1>/<int:pk2>/', ListView.as_view(), name='next-page'),

then you can indeed work with:

<a href="{% url 'next-page' lesson.pk class.pk %}">Link to next page {{lesson}} {{class}}</a>

given of course both lesson and class exist in the context.

  • Related