Dr. Cyanide
Dr. Cyanide

Reputation: 520

Django URL is being changed by a submit button

I'm very new to Django and not super familiar with web programming in general, so it's very likely that there is an easy fix to my problem that I'm just unaware of.

My web app is a photo gallery. People can click on a photo to see an enlarged version with buttons on either side for older or newer pictures. In addition, the photos in the gallery can be sorted by tags, which are passed along as URL parameters.

My problem is that when I click on one of the submit buttons, Django replaces the parameters in my URL with the name of the button, thus destroying my reference to what tag I was using. For example, "127.0.0.1:8000/gallery/view/6/?tag=people" upon clicking next, gets converted to "127.0.0.1:8000/gallery/view/6/?older=Older" when it's trying to process the URL.

Code from my HTML:

<form action="/gallery/view/{{ photo.id }}/?tag={{ tag }}" method="get">
    {% if has_newer %}
    <input type="submit" name="newer" value="Newer">
    {% endif %}

    <img src="{{ photo.photofile.url }}">

    {% if has_older %}
    <input type="submit" name="older" value="Older">
    {% endif %}
</form>

In my view.py I pass in the tag plus other information in a render_to_response, but I'm not sure how to/if I can reclaim it while handling the buttons.

render_to_response('item/view.html', {'photo':photo, 'tag':tag, 'related_tags': related_tags, 'related_photos': related_photos, 'has_newer': has_newer, 'has_older': has_older}, context_instance=RequestContext(request)) 

Here's the view.py code for processing the buttons:

if 'newer' in request.GET:
    if has_newer:   
        return HttpResponseRedirect('/gallery/view/%s/?tag=%s'%(newer[1].id, tag))
    else:
        return HttpResponseRedirect('/gallery/')
if 'older' in request.GET:
    if has_older:
        return HttpResponseRedirect('/gallery/view/%s/?tag=%s'%(older[1].id, tag))
    else:
        return HttpResponseRedirect('/gallery/')

Upvotes: 1

Views: 1088

Answers (1)

Jesse the Game
Jesse the Game

Reputation: 2630

<form action="/gallery/view/{{ photo.id }}/" method="get">
    {% if has_newer %}
    <input type="submit" name="newer" value="Newer">
    {% endif %}

    <!--This will append a tag parameter with given value to the querystring -->
    <input type="hidden" name="tag" value="{{ tag }}">

    <img src="{{ photo.photofile.url }}">

    {% if has_older %}
    <input type="submit" name="older" value="Older">
    {% endif %}
</form>

Note that the query string is removed from action (as it won't be used) and the older and newer parameters will still be sent along.

Upvotes: 1

Related Questions