How To Pass Parameters To View Via Url In Django

Pass paremeters via url in Django is not same as java or php which use question mark and key value pairs ( for example http://127.0.0.1:8080/login.jsp?username=jerry&password=12345678). Django use a more clear, readable and SEO friendly way to pass parameters in url like http://127.0.0.1:8080/login/jerry/12345678. The first section after login is username, and the section after jerry is password. This article will show you how to pass parameters through url in Django.

1. Define Url Pattern In Djanog App urls.py File.

This example is based on Django Bootstrap3 Example, when the code complete, it will add a url link to employee name in the employee list page like below. When user click the employee name, it will display the employee detail information page.

add link to employee user name in the employee list page

So we should add a url pattern in the DjangoHelloWorld / dept_emp / urls.py file.

add dept emp views test case python file

url(r'^emp_detail/(?P<user_name>\w+)/(?P<mobile_number>\d{10,18})/$', views.emp_detail, name='emp_detail'),

Above url pattern means when client request http://……/emp_detail/param1/param2, the request will be processed by views.emp_detail function. And the views.emp_detail function has two additional parameter, one is user_name, the other is mobile_number.

The (?P<user_name>\w+) section means this is a url parameter (?P), and the parameter value should be passed to views.emp_detail function’s user_name argument. The \w+ is a regular expression which means this url parameter’s value should be more than one charactor or digits.

The (?P<mobile_number>\d{10,18}) section means this is a url parameter (?P), and the parameter value should be passed to views.emp_detail function’s mobile_number argument. The \d{10,18} is a regular expression which means this url parameter’s value should be digits only and the digit number’s length should between 10 and 18.

READ :   How To Create / Remove Django Project Application

With this url pattern defined in urls.py file, when client request http://127.0.0.1:8000/dept_emp/emp_detail/jerry/13901234567/, then the request will be processed by views.emp_detail function.

2. Define View Function In Django App views.py File.

Now let us define the emp_detail function in DjangoHelloWorld / dept_emp / views.py file.

''' This function will retrieve employee detail information and return the emp_detail.html page to client.
    This function contains two url parameter user_name and mobile_number.
'''
@login_required()
def emp_detail(request, user_name, mobile_number):

    # define the returned employee object as None.
    emp = None

    # cast the request mobile_number from string to integer type.
    mobile_number_integer = int(mobile_number)

    # filter out the Employee object list with passed in username and mobile number.
    emp_list = Employee.objects.filter(user__username=str(user_name), emp_mobile=mobile_number_integer)

    # if emp_list is empty, then you can use hard coded username and emp_mobile value to test whether the code is correct or not.
    #emp_list = Employee.objects.filter(user__username='jerry', emp_mobile=13901234567)

    # get the returned Employee object.
    if len(emp_list) > 0:
        emp = emp_list[0]
    else:
        emp = None

    # return the emp_detail.html template file to client, and pass the filtered out Employee object.
    return render(request, 'dept_emp/emp_detail.html',
                  {'emp': emp})

3. Define The emp_detail.html Page.

In above views.py emp_detail function, we redirect user to dept_emp/emp_detail.html template page. So we should add this html template in folder DjangoHelloWorld / templates / dept_emp.

department employee manager emp_detail html page

Below is the page content, it will display the employee detail information data in a table. Because this employee may belongs to multiple department, so Employee and Departments object are many to many relationship, so the employee’s department value is retrieved by {{ emp.get_dept_values }}, please read article How To Get Many To Many Model Field Values In Django View.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Employee Detail Information Page</title>
</head>
<body>
{% extends "./base.html" %}
{% block content %}

    <div class="container theme-showcase margin-top-navbar" role="main" style="margin-top: 50px">


    <div class="row">
        <div class="col-md-12">
            <table class="table table-striped">


    {% if emp is not None %}

      <!-- employee detail information-->


                <tr>
                    <td>Id:</td><td>{{ emp.id }}</td>
                </tr>

                <tr>
                    <td>User name:</td><td>{{ emp.user.username }}</td>
                </tr>

                <tr>
                    <td>Mobile number:</td><td>{{ emp.emp_mobile }}</td>
                </tr>

                <tr>
                    <td>Salary:</td><td>{{ emp.emp_salary }}</td>
                </tr>

                <tr>
                    <td>Onboard date:</td><td>{{ emp.emp_onboard_date }}</td>
                </tr>

                <tr>
                    <td>Department:</td><td>{{ emp.get_dept_values }}</td>
                </tr>

    {% else %}
        <tr>
            <td>
                No employee data returned.
            </td>
        </tr>

    {% endif %}
            </table>

            </div>
        </div>
    </div>


{% endblock %}
</body>
</html>

4. Use Django url Tag To Generate Url Link In Template Html Page.

Now we need to add employee name url link in DjangoHelloWorld / templates / dept_emp / emp_list.html page by editing below code.

{% for emp in emp_list %}
      <tr>
          <td><input type="checkbox" id="emp_{{ emp.id }}" name="emp_{{ emp.id }}"></td>
          <td>{{ emp.id }}</td>
          <!-- Because you defined the emp_detail view has two parameter in the url, one is user_name, the other is mobile_number.So use Django url tag to render it. -->
          <td><a href="{% url 'dept_emp:emp_detail' user_name=emp.user.username mobile_number=emp.emp_mobile %}">{{ emp.user.username }}</a></td>
          <td>{{ emp.get_dept_values }}</td>
          <td>{{ emp.emp_mobile }}</td>
          <td>{{ emp.emp_salary }}</td>
          <td>{{ emp.emp_onboard_date }}</td>
      </tr>
{% endfor %}

5. Run The Example.

When you run this example, it will show a url link for the employee name in the employee list page like below.

READ :   How To Use Python ConfigParser To Read Write Configuration File

add link to employee user name in the employee list page

When you click the employee name, it will show below employee detail information page.

employee detail information page

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.