'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.
- If the title comes from the article model then it should look like this:
http://127.0.0.1:8000/article/python-is-amazing - If the title comes from the qa model then it should look like this:
http://127.0.0.1:8000/qa/python-is-amazing - 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)})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
