Convert JSON from Django to JavaScript Array and Loop to Populate 'users' Parameter in Mention.js -
i'm going wrong, need guidance. i'm using mention.js
linking profiles in posts in application i'm building. getting working hard coded data trivial. set described in docs.
well, app, each user logged in belongs organization, , organization comes django json. want populate mention.js
dropdown choose these data when user types, organization list comes up. have json logged terminal console , browser console:
[ { "fields": { "avatar": "images/avatars/bob.png", "name": "bob jones" }, "model": "accounts.profile", "pk": 5 }, { "fields": { "avatar": "images/avatars/sam.png", "name": "sam smith" }, "model": "accounts.profile", "pk": 7 } ]
so i'm getting correct data django. can parse data relatively , print browser console:
console.log(profile_array[0].fields.name);
the next step mention.js
users
parameter. based on @sainaen's answer, have in javascript:
users: profile_array.map(function (profile) { return { username: profile.fields.name, // still missing name: profile.fields.name, image: '/media/' + profile.fields.avatar }; })
the problem profile not have username
field. it's linked user
model onetoone
relationship. in view, i'm returning 2 chunks of json: profiles (for name
, avatar
) , users (for username
).
i realized can combine these json objects , did that.
but i'm having trouble getting username
out users
parameter in mention.js
.
update
to solve this, added username
field profile model. added code save
override autopopulate theusername
of profile model equal user.username
. not sure if best method, allows @sainaen's answer work.
from source of mention.js
looks users
expected array of js objects, no function inside array work. matching performed on username
fields , name
displaying results. think should set not name
-s , avatar
-s, username
-s.
idealy, if django model user contain username
, this:
$("#some-field").mention({ // other fields users: profile_array.map(function (profile) { return { username: profile.fields.username, name: profile.fields.name, avatar: profile.fields.avatar }; }) });
but of course, convert names usernames on js side, like:
// converts names usernames // ex: 'bob jones' -> 'bob_jones' function nametousername(name) { return name.tolowercase().replace(/\s+/g, '_'); }
and use in code creates users
array:
$("#some-field").mention({ // other fields users: profile_array.map(function (profile) { return { username: nametousername(profile.fields.name), name: profile.fields.name, avatar: profile.fields.avatar }; }) });
Comments
Post a Comment