Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you pass two parameters through url in django

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{% 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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading