How To Share Information Between Django and Javascript?

Posted by Randy on Stack Overflow See other posts from Stack Overflow or by Randy
Published on 2011-01-17T04:30:37Z Indexed on 2011/01/17 4:53 UTC
Read the original article Hit count: 275

Filed under:
|
|
|

So I am pretty new to both Django and Javascript (I am using JQuery) and I am wondering if I am doing a hack or if there are more slick ways to send client-side displayed database ids to the django server-side. Here is my process:

I have a dataTable (http://datatables.net) that I am displaying rows of data by using the bProcessing option to use AJAX to retrieve records from the database. The URL in my urls.py is something like:

url(r'^assets/activitylog/(?P<cid>.*)$', views.getActivityTable_ajax, name="activitylog_table"),

and my dataTable ajax-relavant code is something like:

"sAjaxSource": "/assets/activitylog/" + getIDFromHTML(),

where the javascript function getIDFromHTML() grabs <cid> that is used by the Django view is simply:

function getIDFromHTML(){
    // Simply return the text in the #release_id div element from the HTML
    return $("#release_id").html();
};

This is the part that seems "hacky" to me. I am inserting into my template code the database id that I am using in the datatables URL (with display:none in the css) just so I can pass it back to the view. Most of this is necessitated because one cannot use django template tags in the javascript code unless the code is embedded into the HTML itself, which I am not (and will not) do.

The only other thing that I have found is to change the URL to get rid of the parameter passed in to:

url(r'^assets/activitylog', views.getActivityTable_ajax, name="activitylog_table"),

and change the view code to:

def getActivityTable_ajax(request):
    """Returns the activity for a given pid from HTTP GET ajax reqest"""

    pid = int(urlparse.urlparse(request.META['HTTP_REFERER']).path.split('/')[-1])
    # rest of view code here...

since the id that I need is on the end of this referer url.

This way I don't have to monkey around with embedding the hidden database id into the HTML and passing it back to via ajax the the table population view code.

Is it okay to use HTTP_REFERER in the request object in this manner? Am I going about this in the totally wrong way?

Thanks in advance!

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about django