0

I am rendering a template in django 1.7 with a hidden field containing the url of the rendered page . So if i hit a url http://localhost:8080/signin/common?test=true , i need to set the hidden field value to http://localhost:8080/signin/common?test=true

I use jquery in my project and set the location of the page into the variable by doing

<script type="text/javascript">
$(document).ready(function() {
      $("#hiddenfieldId").val(window.location.href);     
});

This sets the value of the hidden field correctly as per the url of the page . I later read that the same thing can be achieved in Django by a Custom request Context Processor. I created a custom request context processor as

def current_page_url(request):
    return {
        'current_page_url': request.build_absolute_uri()
    }

and added it to the TEMPLATE_CONTEXT_PROCESSORS in the settings. On the rendered page i obtained the value of the page url as

<input type="hidden" autocomplete="off" name='hiddenfield' value="{{ current_page_url }}" id="hiddenfieldId"  />

The value gets populated properly in this case as well.I see the value which gets populated by the django context processor and jquery script matching exactly.

In this scenario wanted to understand what it the preferred way or best practice in getting the current page url set in the hidden field on the page (also reasoning for choosing the best practice in the case would be helpful ) ?

jay
  • 791
  • 8
  • 20

1 Answers1

0

Use {{ request.get_host }}{{ request.path }} instead of {{ current_page_url }}. You don't need the function of context processor for this to work. This gets the domain + url for the current page within a template. Didn't use it to assign a value to a hidden field though. Please check to see if this works, and share with us. :)

MiniGunnR
  • 5,590
  • 8
  • 42
  • 66
  • I guess to access request on the template i would be requiring "django-core-context-processors-request ", i read from https://docs.djangoproject.com/en/1.7/ref/templates/api/#django-core-context-processors-request that it is disabled by default , it might be disabled by default for the reasons stated as per http://stackoverflow.com/questions/22292424/why-is-django-core-context-processors-request-not-enabled-by-default. Hence don't think your answer might be the correct answer that i am looking for. – jay Jul 17 '15 at 18:54