How To Pass Multiple Parameters Via Url In Django

If you find the Django url pattern is not easy to use when you want to pass multiple request parameters via url, you can use the original method to implement it. The original method is to use url like this It just add the parameter name and value pair after question mark (?) of the url, and each name value pair is separated by & mark. This article will tell you how to get the request parameter value in Django.

1. Use HttpRequest GET.

Django HttpRequest GET attribute is a dictionary like object that contains all get method request parameters and related values. You can retrieve get method request parameter’s value  like below. If no value is retrieved then return the default value -1.

dept_id = request.GET.get('dept_id', -1)

2. Get Multiple Parameters Via Url Example.

This example is also based on the source code of Django Bootstrap3 Example. It add one feature, that when user click the department name, it will list all the employee belongs to that department.

list department employees

We need to change 3 source files in the example.

django project app dept_emp source files structure

2.1 DjangoHelloWorld / dept_emp /

Change employee list url pattern in dept_emp / as below.

# request will invoke the emp_list function defined in
url(r'^emp_list/', views.emp_list, name='emp_list'),

2.2 DjangoHelloWorld / dept_emp /

Change the emp_list function to below code.

def emp_list(request):
    dept_id = request.GET.get('dept_id', -1)
    # list all employee.
    if dept_id == -1:
        emp_list = Employee.objects.all()
        return render(request, 'dept_emp/emp_list.html',
                      {'emp_list': emp_list})
    # list special department employee.
        # return Department object which id equals to the dept_id
        dept_list = Department.objects.filter(id = dept_id)

        # create an empty employee list object.
        emp_list = list()

        if len(dept_list) > 0:
            dept = dept_list[0]

            # return the employee list of this department.
            emp_list = Employee.objects.filter(dept=dept)

        return render(request, 'dept_emp/emp_list.html',
                      {'emp_list': emp_list})

2.3 DjangoHelloWorld / templates / dept_emp / dept_list.html

Add href link when render the department name in the loop. And add the request parameter dept_id with it’s value.

<td><a href="{% url 'dept_emp:emp_list' %}?dept_id={{ }}">{{ dept.dept_name }}</a></td>
{% for dept in dept_list %}
         <td><input type="checkbox" id="dept_{{ }}" name="dept_{{ }}"></td>
         <td>{{ }}</td>
         <td><a href="{% url 'dept_emp:emp_list' %}?dept_id={{ }}">{{ dept.dept_name }}</a></td>
         <td>{{ dept.dept_desc }}</td>
{% endfor %}
READ :   How To Show SQL Query Command In Django Migration

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.