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