Seth
Seth

Reputation: 6842

How can I pass named arguments to a Django view method?

I have a view method with two additional parameters:

def foo(request, email, token):
    ...

And I need to use reverse to generate a URL:

    ...
    url = urlresolvers.reverse(
        'my_app.views.foo',
        kwargs={ 'token': <token>, 'email': <email> })
  1. Is my use of reverse reasonable/acceptable, and
  2. What does the URL pattern for foo look like?

Upvotes: 1

Views: 1774

Answers (2)

professorDante
professorDante

Reputation: 2405

1 - Yes, as far as it goes, but of course it will fail without the urlpattern. You can use either args or kwargs, depending on your case. Here you can use args, as they are both required args from your view function.

2 - Here's a urlpattern to get you going, but the regex is only an example, as I don't know what your regex needs to be.

url(r'^/(?P<email>[-\w]+)/(?P<token>\d{1,2})/$', 'views.foo', name='foo'),

Named urls are a good pattern to get into the habit of doing. You can pass the name to the reverse function too:

url = urlresolvers.reverse(
    'foo',
    args=['<email>', '<token>']

Upvotes: 3

Germano
Germano

Reputation: 2482

  1. Yes
  2. It's up to you to write it in your URLconf. You might want to have a look at Django docs

By your question, though, it's probably better if you run through the tutorial. The third part explains how to write down the URL scheme for your site.

Upvotes: 0

Related Questions