pythondjangourl-mapping

passing a parameter from html page url mapping to the views in django


front.html

<div class="row">
   <a href="{% url 'emp_pay_list' Information_technology %}">
      <div class="col-md-6 col-sm-6 col-lg-3">
        <div class="dash-widget clearfix card-box" style="height: 200px;">
            <span class="dash-widget-icon"><i class="fa fa-cubes" aria-hidden="true"></i></span>
            <div class="dash-widget-info">
                <h3>20</h3>
                <span>Information Technology</span>
            </div>
        </div>
      </div>
   </a>

   <a href="{% url 'emp_pay_list' sales %}">
       <div class="col-md-6 col-sm-6 col-lg-3">
          <div class="dash-widget clearfix card-box" style="height: 200px;">
              <span class="dash-widget-icon"><i class="fa fa-users" aria-hidden="true"></i></span>
              <div class="dash-widget-info">
                 <h3>7</h3>
                  <span>Sales Team</span>
              </div>
          </div>
       </div>
    </a>
</div>

The above code is the front end part HTML here I want to pass a parameter into the urls.py by clicking a box and depends on the parameter which we pass the data should be fetched.

urls.py

url(r'^list_of_employees/<string>/$', views.Pay_slip_list , name='emp_pay_list'),

This is the code which I am using in urls.py to pass parameter.

views.py

def Pay_slip_list(request, department):
    hello = employees.objects.select_related('employee_name', 'employee_auth').filter(department=department)
    return render(request, 'hr/emp_pay_list.html', {'hello': hello})

And this is the views.py part where I am fetching data from the database based on the string/parameter passed after clicking the box.


Solution

  • Your URL pattern must look like

    from django.urls import path, re_path
    
    path('list_of_employees/<str:department>/', views.Pay_slip_list , name='emp_pay_list'),
    

    or use re_path

    re_path(r'^list_of_employees/(?P<department>[\w\-]+)/$', views.Pay_slip_list , name='emp_pay_list')
    

    use path instead of url for Django version >= 2.0, or use re_path for complex patterns, re_path is same as url method in lower versions