Asma Gheisari
Asma Gheisari

Reputation: 6254

pass view parameters when using it's url in templates

in views.py I have this:

def logout(request,key):
   auth.logout(request)
   return HttpResponseRedirect(reverse('airAgency.views.index',args=[key])) 

in index template i wanna when user click on a link,logout view run:

<a href="{% url airAgency.views.logout %}">logout</a>

I wanna pass key parameter to logout view,Imagine I have an object named agn and it's WebSite field is going to pass to logout view, s.th like this:

<a href="{% url airAgency.views.logout agn.WebSite %}">

Imagine agn.WebSite has the value of mastane above code cause this error:

Caught NoReverseMatch while rendering: Reverse for 'airAgency.views.logout' with arguments '(u'mastane',)' and keyword arguments '{}' not found.

what's the right way to do this?

Upvotes: 0

Views: 258

Answers (1)

Ska
Ska

Reputation: 6888

Caught NoReverseMatch - usually means that the url is being called by incorrect arguments, or that something else is wrong when {% url %} tries to call the url specified.

You need to define url pattern for that view function to be called in urls.py. And in the url pattern specify a view function.

urls.py

url(r'^logout/(?P<key>[a-zA-Z0-9\-]+)/$', "airAgency.views.logout", name="logout"),

index.html

<a href="{% url logout agn.WebSite %}">

This might not work if you just copy paste it because I don't know the exact project setup.

The key is to have urls.py where regex is used to create patterns for how the url looks like, then a view function that needs to be invoked, and finally a name, which you can then use in your templates.

This is all explained in the basic Django tutorial.

Upvotes: 1

Related Questions