简体   繁体   中英

How can I reverse django admin url with url parameters to prepopulate some fields?

I have Transaction app and Transaction model. Transaction model has foreign key to User model. I noticed that I can prepopulate some fields with data through GET parameters. For example to choose user for my transaction in admin form I can use this url:

transactions/transaction/add/?user=1

It work fine, but I want to user reverse function to generate that kind of urls.

Tried this:

from django.urls import reverse
reverse('admin:transactions_transaction_add', kwargs={'user': 1})

But got this error:

Reverse for 'transactions_transaction_add' with arguments '()' 
and keyword arguments '{'user': 1}' not found. 1 pattern(s)
tried: ['admin/transactions/transaction/add/$']

I made this work to use concatenate generated link:

change_url = reverse(
        "admin:transactions_transaction_add",
    ) + "?user=" + str(obj.pk)

But would be very kind to know if the more clear solution for this. Note that 'transactions/transaction/add/?user=1' works just fine if use it from browser, error appears for reverse function.

Thanks!

Try this solution from a previous asked question.

url = reverse('object_detail', 
              kwargs={'foo':'bar'}, 
              current_app=app_name_or_name_space)

or try the official documentation

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