简体   繁体   中英

Passing multiple arguments from django template href link to view

I am trying to pass some arguments with a link url href in a template to a view.

In my template :

 <a href="/print-permission-document/ studentname={{studentinfo.0}} studentsurname={{studentinfo.1}} studentclass={{studentinfo.2}} doctype=doctype-studentlatepermission">Print</a>

So i am trying to pass 4 arguments to my view.

My view is :

def print_permission_document(request, studentname, studentsurname, studentclass, doctype):
file_write(studentname.encode('utf-8')+" "+studentsurname.encode('utf-8')+" "+studentclass+" "+doctype)
return response

My urls.py is :

url(r'^print-permission-document/.+$', print_permission_document, name='print-permission-document')

But i get below error :

Exception Type: TypeError Exception Value:
print_permission_document() takes exactly 5 arguments (1 given)

This is not how you specify multiple parameters in a URL, typically you write these in the URL, like:

url(
    r'^print-permission-document/(?P<studentname>\w+)/(?P<studentsurname>\w+)/(?P<studentclass>\w+)/(?P<doctype>[\w-]+)/$',
    print_permission_document, name='print-permission-document'
)

Then you generate the corresponding URL with:

<a href="{% url 'print-permission-document' studentname=studentinfo.0 studentsurname=studentinfo.1 studentclass=studentinfo.2 doctype='doctype-studentlatepermission' %}">Print</a>

This will then generate a URL that looks like:

/print-permission-document/somename/someclass/doctype-studentlatepermission

Typically a path does not contain key-value pairs, and if it does, you will need to "decode" these yourself.

You can also generate a querystring (after the question mark), these you can then access in request.GET [Django-doc] .

You are passing your URL wrongly. and URL in template is also declared wrongly.

Try this

<a href="{% url 'print-permission-document' studentinfo1, studentinfo2, ... %}">Print</a>

url(
    r'^print-permission-document/(?P<studentname>\w+)/(?P<studentsurname>\w+)/(?P<studentclass>\w+)/(?P<doctype>\w+)/$',
    print_permission_document, name='print-permission-document'
)

I had the same error , i corrected it by :

url(r'^auth_app/remove_user/(?P<username2>[-\w]+)/$', views.remove_user, name="remove_user"),

Use this pattern for passing string

(?P<username2>[-\w]+)

This for interger value

(?P<user_id>[0-9]+)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM