views:

34

answers:

1

Hello,

I am working on a project that requires me to use a value contained in a variable from my view.py template. I need to use that variable in my javascript. Does anyone know a proper way to pass a variable from django to JS?

Here is my function in views.py

@login_required
@never_cache_headers
def user_feed(request, user=None, extension=None):
# Ensure we have a user
if user is None:
    user = request.user
    prof = user.get_profile()
elif isinstance(user, basestring):
    user = get_object_or_404(User, id=user)

# Build author list
author_ids = []
author_ids.append(user.id)

# Check if user if friend to profile being viewed
are_friends = Friendship.objects.are_friends(user, request.user)

# Determine Date
now = datetime.datetime.now()
today = now.date()
if now.time() < datetime.time(3):
    start_dt = datetime.datetime.now() - datetime.timedelta(hours=settings.FEEDITEM_BUFFER_HOURS)
else:
    start_dt = datetime.datetime(today.year, today.month, today.day)

# Build up the where query
where = [] 
if user.id != request.user.id:
    where.append({'ping_type':'public'})
    if are_friends: 
        where.append({'ping_type': 'friends_only'})
        where.append({'ping_type': 'invite_only', 'invite_list': request.user.id})
    where = {'$or': where}
else: where = {} # Vanity check - show all pings by author

where['author'] = { '$in' : author_ids }
where['starts'] = { "$gt":start_dt }
where['deleted'] = { "$ne": True }
# print "User View Where = ", where

feeditems, has_more = ds.Feed.feeditems(request, where)

feeditems = ds.FeedItem.prepare(feeditems)
friend_requested = FriendshipInvitation.objects.is_friend_requested(request.user, user)

if extension:
  if extension == 'json':
    return http.HttpResponse(json.dumps(feeditems, indent=2, default=json_handler),
                        mimetype='application/json')
else:
  return render_to_response("social/feeditems_list.html", {
    'feeditems':feeditems,
    'user':user,
    'has_more':has_more,
    'section':'user_feed',
    'are_friends':are_friends,
    'friend_requested':friend_requested,
}, request)

I basically need to pass request.user.id or user.id to Javascript.

EDIT

Actually, I would rather pass it to javascript as its own little one element json array, if thats possible

+4  A: 

Maybe a little obvious, but how about:

<script type="text/javascript">
    var userId = {{ user.id|default:null }};
</script>
WoLpH
Or, if you're using jQuery, look at the .data() method to store data in the DOM, rather than declaring it as a global variable. But, really, the sky won't fall down even if you do use a global. I'd set default:'null' though, to make it easier to handle in JS
stevejalim
I get a parse error with that solution:invalid property id[Break on this error] var userId = {{ request.user.id|default:0 }};\n
fordays
is there anything I need to do on the django side to make sure it's available to be referenced in JS?
fordays
The `RequestContext` in Django should provide you with `request.user`. Since you are already providing `user` you could also use that.
WoLpH