user1662290
user1662290

Reputation: 474

Send data from template to a view django

In my application data about a entry is displayed detailing their information. You can navigate between the entries via a hyperlink. So far the code:

<a href="/parks/{{ park.id }} ">{{park.name}}</a>

Has been suffient in dealing with this. The id is captured in the urls.py and onto views.py

The problem I now face is to deal with my 'location' entry. Examples of locations are 'Europe, UK', 'USA, New York'. I know that:

<a href="/parks/{{ park.location }} ">{{park.location}}</a>

with:

url(r'^location/(?P<park_location>\d+)$', Location_Main),

won't work, due to the spaces and commas etc.

How would I resolve this? I would also like the 'location' view and 'location' url to handle the location of a parent company say ()

Thanks in advance

Upvotes: 1

Views: 4157

Answers (4)

Aamir Rind
Aamir Rind

Reputation: 39659

Why not pass pass park.id and then in view get the park object and then get its location:

the url:

url(r'^location/(?P<park_id>\d+)$', Location_Main, name="park_location"),

the template:

<a href="{% url park_location park.id %}">{{park.location}}</a>

the view:

def Location_Main(request, park_id):
    park = get_object_or_404(Park, pk=park_id)
    location = park.location

Alternatively send the location as GET parameter:

the url:

url(r'^location/$', Location_Main, name="park_location"),

the template:

<a href="{% url park_location %}?location={{park.location}}">{{park.location}}</a>

the view:

def Location_Main(request):
    location = request.GET.get('location')

Upvotes: 6

Rohan
Rohan

Reputation: 53316

You can use urlencode template filter to escape the characters as

<a href="/parks/{{ park.location|urlencode }} ">{{park.location}}</a>

With reference to this question you may have to change the url pattern as

url(r'^location/(?P<park_location>[\w|\W]+)$', Location_Main)

Upvotes: 0

avenger
avenger

Reputation: 120

You will need to remove punctuation and non-english characters from the location names before using them in the url. Alternatively you can remove them when you define park.location.

Upvotes: 0

catherine
catherine

Reputation: 22808

 url(r'^location/(?P<park_location>[a-zA-Z0-9_.-]+)/$', Location_Main),

Upvotes: 1

Related Questions