zurfyx
zurfyx

Reputation: 32787

Django urls keywords

With the following Django code, I have a problem when passing a url keyword to the template.

views.py

def index(request,username):
    return render(request,'myaccount.html')

urls.py from projectname folder

urlpatterns = patterns('',
    url(r'^myaccount/',include('myaccount.urls')),
)

urls.py from myaccount app

urlpatterns = patterns('',
    url(r'^(?P<username>[a-zA-Z0-9]+)/$','myaccount.views.index',name='myaccount'),
)

The question is, why when I use the following html code it shows /myaccount/Jerry/

myaccount.html

    {% url 'myaccount' 'Jerry' %}

but it shows error when I pass the keyword?

myaccount.html

    {% url 'myaccount' username %}

NoReverseMatch at /myaccount/Jerry/
Reverse for 'myaccount' with arguments '('',)' and keyword arguments '{}' not found.

The error gets fixed when I pass the variable username like that:

def index(request,username):
    return render(request,'myaccount.html',{'username':username})

But, is there a faster way?

Upvotes: 1

Views: 2852

Answers (1)

Paul Renton
Paul Renton

Reputation: 2670

In your regex you are capturing a key/value pair where the key is equal to username. You need to specify username='Jerry' in your url tag.

The P < username > means capture the following and link it to a keyword called username.

{% url 'myaccount' username='Jerry' %}

So in your case, if you don't provide a keyword argument for the Reverse look-up, it will look for a regex pattern that does not exist.

EDIT

This may address your 'faster way' concern. You should try using a Class Based View. See https://docs.djangoproject.com/en/1.5/ref/class-based-views/base/#django.views.generic.base.TemplateView

If one were to use the url pattern->

    url(r'^(?P<somenumber>\d+)/test/$', views.TestView.as_view(), name='testview')

Where TestView is defined in views.py as (Be sure to import views in your url.py)

from django.views.generic import TemplateView
class TestView(TemplateView):
    model = xxxx // link to your model here
    template_name = 'test.html'

In the test.html template you just have to do this

{{ somenumber }}

to extract the value of the passed in argument.

The get_context_data(self, **kwargs) function of the TemplateView will autmatically update the context of the template to include any key/value pair arguments found in your url pattern.

In fact, you can override this function and call super to update any custom k/w arguments you want in the template context.

Upvotes: 2

Related Questions