Home > Blockchain >  Could not parse the remainder: '${profiles['user']}' from '${profiles['
Could not parse the remainder: '${profiles['user']}' from '${profiles['

Time:01-12

    const data = '{{ search_user }}'
    const rdata = JSON.parse(data.replace(/"/g, '"'))
    const input = document.getElementById('user-input_products')

    let filteredArr = []

    input.addEventListener('keyup', (e)=>{
        box.innerHTML = ""
        filterMax = (fn, c) => x => c && fn(x) && c--
        filter = profiles=> profiles['full_name'].includes(e.target.value)
        max = 30
        filteredArr = rdata.filter(filterMax(filter, max))
        if (filteredArr.length > 0) {
            filteredArr.map(profiles=>{
                box.innerHTML  = `<li><a href="{% url 'user_num' ${profiles['user']} %}">${profiles['full_name']}</a></li>`
            })
        } else {
            box.innerHTML = "No result found"
        }
    })

And when i want to pass id to django url inside of innerHTML it's give me this error:

Could not parse the remainder: '${profiles["user"]}' from '${profiles["user"]}'

How can i fix that?

rdata:
[
  {
    "user": 28,
    "full_name": "John"
  },
  {
    "user": 35,
    "full_name": "Robert"
  },
  {
    "user": 37,
    "full_name": "Mary"
  },
  {
    "user": 38,
    "full_name": "Jennifer"
  },
]

CodePudding user response:

You cannot mix server side Python code with frontend javascript code like this. Django Templates sees ${profiles['user']} as a simple string. To fix this you can store a path prefix in a JS variable and combine the user links with JS template literal:

const path_prefix = "{% url 'user_num' %}"
const data = '{{ search_user }}'
const rdata = JSON.parse(data.replace(/&quot;/g, '"'))
const input = document.getElementById('user-input_products')

let filteredArr = []

input.addEventListener('keyup', (e)=>{
    box.innerHTML = ""
    filterMax = (fn, c) => x => c && fn(x) && c--
    filter = profiles=> profiles['full_name'].includes(e.target.value)
    max = 30
    filteredArr = rdata.filter(filterMax(filter, max))
    if (filteredArr.length > 0) {
        filteredArr.map(profiles=>{
            box.innerHTML  = `<li><a href="${path_prefix}${profiles['user']}">${profiles['full_name']}</a></li>`
        })
    } else {
        box.innerHTML = "No result found"
    }
})

If the path for the user_num view function is user_num/, then ${path_prefix}${profiles['user']} will produce e.g. user_num/28. You may have to create a new URL definition if user_num function requires an argument, or you can just put in the actual path directly, e.g.: user_num/${profiles['user']}.

  •  Tags:  
  • Related