0

Is it possible to get a variable in a URL to pass to a view. For example. I have a location table with many locations. If I click a location it goes to a details page of that location. The location ID gets added to the URL. I then have a link to another page/view but want to reference the location id in the next view.

urls.py:

url(r'^locations/get/(?P<location_id>\d+)/$', 'assessments.views.location'),
url(r'^locations/get/(?P<location_id>\d+)/next_page/$', 'assessments.views.next_page'),

view.py:

def location(request, location_id=1):
    return render_to_response('dashboard/location.html', {'location': Location.objects.get(id=location_id) })

def next_page(request):
    loc = Location.objects.get(id='id of that location')
3
  • Which location do you need in next_page() - location_id or some other one? Commented Sep 16, 2014 at 20:48
  • I need the location of the location i was on before going to the next page. Not sure if that makes any sense. Commented Sep 16, 2014 at 20:52
  • next_page takes exactly the same location_id argument as the original location function does, so you can use it in exactly the same way. Commented Sep 16, 2014 at 20:56

2 Answers 2

1

Simply access it in the view function with its name

def next_page(request,location_id):
    loc = Location.objects.get(id=location_id)
Sign up to request clarification or add additional context in comments.

Comments

1

OK, I'm still not sure what exactly do you mean but I think one of the following two snippets should solve your problem:

  1. The URL contains location_id so just use it in next_page():

    def location(request, location_id):
        return render_to_response('dashboard/location.html', {'location': Location.objects.get(id=location_id) })
    
    def next_page(request, location_id):
        loc = Location.objects.get(id=location_id)
    
  2. Pass location_id in request.session:

    def location(request, location_id):
        request.session['selected_location'] = location_id
        return render_to_response('dashboard/location.html', {'location': Location.objects.get(id=location_id) })
    
    def next_page(request):
        try: 
            selected_location = request.session['selected_location']
        except KeyError:
            # Not sure if 404 is the best status code here but you get the idea
            raise Http404
        loc = Location.objects.get(id=selected_location)
    

1 Comment

Some how i convinced myself that it was so much more complicated. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.