Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
Create Django URL inside JS function based on 3 different models

I have a function that displays titles from 3 different models in Django. I want to add a link to each title so it redirects the user to the proper URL.

The search_autocomplete function returns all titles properly in 1 list, however, I am struggling with the creation of the URL address in the js file. I am using this library to create a list of titles.

Let's say that the user puts "python is amazing" in the search bar. The URL address should contain rootURl/modelUrl/slug.

  1. If the title comes from the article model then it should look like this: http://127.0.0.1:8000/article/python-is-amazing
  2. If the title comes from the qa model then it should look like this: http://127.0.0.1:8000/qa/python-is-amazing
  3. If the title comes from the video model then it should look like this: http://127.0.0.1:8000/video/python-is-amazing

The second issue is that I want to display a list of titles in autocomplete list but I need to pass the slug field to the URL address. How can I do that?

js file

//root URL
const rootUrl = 'http://127.0.0.1:8000'
//models URLs
const articleURL = 'article'
const qaURL = 'qa'
const videoURL = 'video'

new Autocomplete('#autocomplete', {
search: input => {

    const url = `/search/?title=${input}`
    return new Promise(resolve => {
    if (input.length < 3) {
        return resolve([])
    }

    fetch(url)
        .then(response => response.json())
        .then(data => {
        resolve(data.data)
        })
    })
},

onSubmit: result => {
    window.open(`${rootbUrl}/${qaURL}/${encodeURI(result)}`)
},

autoSelect: true
})

views.py

def search_autocomplete(request):
query = request.GET.get('title')
search_list = []
if query:
    article_list = Article.objects.search_one(query=query).order_by('-publish')
    qa_list = QA.objects.search_one(query=query).order_by('-publish')
    video_list = Video.objects.search_one(query=query).order_by('-publish')
    
    search_list = map(lambda x: x.title, chain(article_list, qa_list, video_list))
        
return JsonResponse({'status':200, 'data': list(search_list)})
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!