get_queryset() from a js text input










0















In this step I'm trying to avoid making a form to send data over to django from the frontend.
Ideally I would like to pass a simple string to the queryset with an onclick button, so I can make the tag filters on my Post model and show the ones with the tags from the string input. (just send the string to the queryset, I can deal with the split() and strip() to make it valid)



The simplified html would be something like



<input type="text" name="tag_filter">
<button type="button" onclick="Tag_Filter()">Filter</button>

<script>

function Tag_Filter()
var tags;
tags = document.getElementById("tag_filter");


</script>


And the ListView



class PostListView(ListView):
model = Post #.objects.filter(tags__name__in=["black&white", "red"]).distinct()
template_name = 'post/home.html' # <app>/<model>_<viewtype>.html
#queryset = Post.objects.all()
context_object_name = 'posts'
#ordering = ['-date_posted']

def get_queryset(self):
tag_list = #the return from the Tag_Filter() js
return Post.objects.filter(tags__name__in=tag_list).annotate(num_tags=Count('tags')).filter(num_tags__gte=len(tag_list)).order_by('-date_posted').distinct()


urls.py



urlpatterns = [
path('', PostListView.as_view(), name='post-home'),
other_paths()
]









share|improve this question
























  • in this i suggest use ajax, send your data(filter) to url this url call to def search(request):........... and this get the query and return by JsonResponse to ajax...

    – Diego Avila
    Nov 15 '18 at 16:50











  • Most of the documentation and solutions I've read online suggest using ajax, but I haven't worked with it previously so I don't know how exactly implement it in this case

    – amartini
    Nov 15 '18 at 17:15











  • ok i'm write a answer with an example for you..!!

    – Diego Avila
    Nov 15 '18 at 18:30















0















In this step I'm trying to avoid making a form to send data over to django from the frontend.
Ideally I would like to pass a simple string to the queryset with an onclick button, so I can make the tag filters on my Post model and show the ones with the tags from the string input. (just send the string to the queryset, I can deal with the split() and strip() to make it valid)



The simplified html would be something like



<input type="text" name="tag_filter">
<button type="button" onclick="Tag_Filter()">Filter</button>

<script>

function Tag_Filter()
var tags;
tags = document.getElementById("tag_filter");


</script>


And the ListView



class PostListView(ListView):
model = Post #.objects.filter(tags__name__in=["black&white", "red"]).distinct()
template_name = 'post/home.html' # <app>/<model>_<viewtype>.html
#queryset = Post.objects.all()
context_object_name = 'posts'
#ordering = ['-date_posted']

def get_queryset(self):
tag_list = #the return from the Tag_Filter() js
return Post.objects.filter(tags__name__in=tag_list).annotate(num_tags=Count('tags')).filter(num_tags__gte=len(tag_list)).order_by('-date_posted').distinct()


urls.py



urlpatterns = [
path('', PostListView.as_view(), name='post-home'),
other_paths()
]









share|improve this question
























  • in this i suggest use ajax, send your data(filter) to url this url call to def search(request):........... and this get the query and return by JsonResponse to ajax...

    – Diego Avila
    Nov 15 '18 at 16:50











  • Most of the documentation and solutions I've read online suggest using ajax, but I haven't worked with it previously so I don't know how exactly implement it in this case

    – amartini
    Nov 15 '18 at 17:15











  • ok i'm write a answer with an example for you..!!

    – Diego Avila
    Nov 15 '18 at 18:30













0












0








0








In this step I'm trying to avoid making a form to send data over to django from the frontend.
Ideally I would like to pass a simple string to the queryset with an onclick button, so I can make the tag filters on my Post model and show the ones with the tags from the string input. (just send the string to the queryset, I can deal with the split() and strip() to make it valid)



The simplified html would be something like



<input type="text" name="tag_filter">
<button type="button" onclick="Tag_Filter()">Filter</button>

<script>

function Tag_Filter()
var tags;
tags = document.getElementById("tag_filter");


</script>


And the ListView



class PostListView(ListView):
model = Post #.objects.filter(tags__name__in=["black&white", "red"]).distinct()
template_name = 'post/home.html' # <app>/<model>_<viewtype>.html
#queryset = Post.objects.all()
context_object_name = 'posts'
#ordering = ['-date_posted']

def get_queryset(self):
tag_list = #the return from the Tag_Filter() js
return Post.objects.filter(tags__name__in=tag_list).annotate(num_tags=Count('tags')).filter(num_tags__gte=len(tag_list)).order_by('-date_posted').distinct()


urls.py



urlpatterns = [
path('', PostListView.as_view(), name='post-home'),
other_paths()
]









share|improve this question
















In this step I'm trying to avoid making a form to send data over to django from the frontend.
Ideally I would like to pass a simple string to the queryset with an onclick button, so I can make the tag filters on my Post model and show the ones with the tags from the string input. (just send the string to the queryset, I can deal with the split() and strip() to make it valid)



The simplified html would be something like



<input type="text" name="tag_filter">
<button type="button" onclick="Tag_Filter()">Filter</button>

<script>

function Tag_Filter()
var tags;
tags = document.getElementById("tag_filter");


</script>


And the ListView



class PostListView(ListView):
model = Post #.objects.filter(tags__name__in=["black&white", "red"]).distinct()
template_name = 'post/home.html' # <app>/<model>_<viewtype>.html
#queryset = Post.objects.all()
context_object_name = 'posts'
#ordering = ['-date_posted']

def get_queryset(self):
tag_list = #the return from the Tag_Filter() js
return Post.objects.filter(tags__name__in=tag_list).annotate(num_tags=Count('tags')).filter(num_tags__gte=len(tag_list)).order_by('-date_posted').distinct()


urls.py



urlpatterns = [
path('', PostListView.as_view(), name='post-home'),
other_paths()
]






javascript django






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 22:59







amartini

















asked Nov 15 '18 at 16:21









amartiniamartini

12




12












  • in this i suggest use ajax, send your data(filter) to url this url call to def search(request):........... and this get the query and return by JsonResponse to ajax...

    – Diego Avila
    Nov 15 '18 at 16:50











  • Most of the documentation and solutions I've read online suggest using ajax, but I haven't worked with it previously so I don't know how exactly implement it in this case

    – amartini
    Nov 15 '18 at 17:15











  • ok i'm write a answer with an example for you..!!

    – Diego Avila
    Nov 15 '18 at 18:30

















  • in this i suggest use ajax, send your data(filter) to url this url call to def search(request):........... and this get the query and return by JsonResponse to ajax...

    – Diego Avila
    Nov 15 '18 at 16:50











  • Most of the documentation and solutions I've read online suggest using ajax, but I haven't worked with it previously so I don't know how exactly implement it in this case

    – amartini
    Nov 15 '18 at 17:15











  • ok i'm write a answer with an example for you..!!

    – Diego Avila
    Nov 15 '18 at 18:30
















in this i suggest use ajax, send your data(filter) to url this url call to def search(request):........... and this get the query and return by JsonResponse to ajax...

– Diego Avila
Nov 15 '18 at 16:50





in this i suggest use ajax, send your data(filter) to url this url call to def search(request):........... and this get the query and return by JsonResponse to ajax...

– Diego Avila
Nov 15 '18 at 16:50













Most of the documentation and solutions I've read online suggest using ajax, but I haven't worked with it previously so I don't know how exactly implement it in this case

– amartini
Nov 15 '18 at 17:15





Most of the documentation and solutions I've read online suggest using ajax, but I haven't worked with it previously so I don't know how exactly implement it in this case

– amartini
Nov 15 '18 at 17:15













ok i'm write a answer with an example for you..!!

– Diego Avila
Nov 15 '18 at 18:30





ok i'm write a answer with an example for you..!!

– Diego Avila
Nov 15 '18 at 18:30












1 Answer
1






active

oldest

votes


















0














I suggest use ajax, then your first step is implement ajax ...ajax is from Jquery then you need include the jquery on your template only for one file html or if your prefer in your base.html on the end of file before from your body end tag:



<!-- jQuery library -->
<script src="% static 'Jquery/jquery.min.js' %"></script>
....
...
all my files js
....
</body>
</html>


for download this jquery.min.js , please go to this link and save the file in to folder: static/Jquery/:



Link for download Jquery min.js



Don't forget save as jquery.min.js



The next is setup your settings.py for accept the static files:



STATIC_URL = '/static/'

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/static/',
]


the next is put the tag for load static files on the top of your file html or base.html as you wish:



% load staticfiles %
<!DOCTYPE html>
<html>
...
...
...
<!-- jQuery library -->
<script src="% static 'Jquery/jquery.min.js' %"></script>
....
...
all my files js
....
</body>
</html>


ok, now we include $.ajax first you need include on your button a function that recive your value from your input:



<input type="text" name="tag_filter" id ="tag_filter">
<button type="button" onclick="tag_filter()">Filter</button>


now your function tag_filter:



 function getCookie(name) 

var cookieValue = null;
if (document.cookie && document.cookie != '')
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++)
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '='))
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;



//RETURN YOUR TOKEN FROM DJANGO FOR SEND FROM AJAX
return cookieValue;

//end function getCookie

function tag_filter()
var tag_filter = $("#tag_filter").val();
if(tag_filter == ''


now you need create a def for search with the parameter example:



from django.http import HttpResponse, JsonResponse

...
..
def SearchFilter(request):
filter = request.GET['tag_filter']
....
....
data =
'result':'ok_select'
'data': #your query

return JsonResponse(data, safe=False)


now you need declare this def on yours urls.py example:



from myapp.views import SearchFilter
urlpatterns = [
url(r'^search_filter', SearchFilter, name='search_filter'),
...
...
]


this is all... on the case of ajax this return success answer by console check this answer on the console from your web browser favorite..



and good luck..!!






share|improve this answer

























  • I'm working with class-based views, there's the main problem I'm having because I don't really know how the request is handled by the ListView class I'm inheriting from. I can't find a way to make the: filter = request.GET['tag_filter'] and get the dictionary from the JSON Everything you wrote helped though

    – amartini
    Nov 15 '18 at 22:28











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53323750%2fget-queryset-from-a-js-text-input%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














I suggest use ajax, then your first step is implement ajax ...ajax is from Jquery then you need include the jquery on your template only for one file html or if your prefer in your base.html on the end of file before from your body end tag:



<!-- jQuery library -->
<script src="% static 'Jquery/jquery.min.js' %"></script>
....
...
all my files js
....
</body>
</html>


for download this jquery.min.js , please go to this link and save the file in to folder: static/Jquery/:



Link for download Jquery min.js



Don't forget save as jquery.min.js



The next is setup your settings.py for accept the static files:



STATIC_URL = '/static/'

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/static/',
]


the next is put the tag for load static files on the top of your file html or base.html as you wish:



% load staticfiles %
<!DOCTYPE html>
<html>
...
...
...
<!-- jQuery library -->
<script src="% static 'Jquery/jquery.min.js' %"></script>
....
...
all my files js
....
</body>
</html>


ok, now we include $.ajax first you need include on your button a function that recive your value from your input:



<input type="text" name="tag_filter" id ="tag_filter">
<button type="button" onclick="tag_filter()">Filter</button>


now your function tag_filter:



 function getCookie(name) 

var cookieValue = null;
if (document.cookie && document.cookie != '')
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++)
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '='))
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;



//RETURN YOUR TOKEN FROM DJANGO FOR SEND FROM AJAX
return cookieValue;

//end function getCookie

function tag_filter()
var tag_filter = $("#tag_filter").val();
if(tag_filter == ''


now you need create a def for search with the parameter example:



from django.http import HttpResponse, JsonResponse

...
..
def SearchFilter(request):
filter = request.GET['tag_filter']
....
....
data =
'result':'ok_select'
'data': #your query

return JsonResponse(data, safe=False)


now you need declare this def on yours urls.py example:



from myapp.views import SearchFilter
urlpatterns = [
url(r'^search_filter', SearchFilter, name='search_filter'),
...
...
]


this is all... on the case of ajax this return success answer by console check this answer on the console from your web browser favorite..



and good luck..!!






share|improve this answer

























  • I'm working with class-based views, there's the main problem I'm having because I don't really know how the request is handled by the ListView class I'm inheriting from. I can't find a way to make the: filter = request.GET['tag_filter'] and get the dictionary from the JSON Everything you wrote helped though

    – amartini
    Nov 15 '18 at 22:28
















0














I suggest use ajax, then your first step is implement ajax ...ajax is from Jquery then you need include the jquery on your template only for one file html or if your prefer in your base.html on the end of file before from your body end tag:



<!-- jQuery library -->
<script src="% static 'Jquery/jquery.min.js' %"></script>
....
...
all my files js
....
</body>
</html>


for download this jquery.min.js , please go to this link and save the file in to folder: static/Jquery/:



Link for download Jquery min.js



Don't forget save as jquery.min.js



The next is setup your settings.py for accept the static files:



STATIC_URL = '/static/'

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/static/',
]


the next is put the tag for load static files on the top of your file html or base.html as you wish:



% load staticfiles %
<!DOCTYPE html>
<html>
...
...
...
<!-- jQuery library -->
<script src="% static 'Jquery/jquery.min.js' %"></script>
....
...
all my files js
....
</body>
</html>


ok, now we include $.ajax first you need include on your button a function that recive your value from your input:



<input type="text" name="tag_filter" id ="tag_filter">
<button type="button" onclick="tag_filter()">Filter</button>


now your function tag_filter:



 function getCookie(name) 

var cookieValue = null;
if (document.cookie && document.cookie != '')
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++)
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '='))
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;



//RETURN YOUR TOKEN FROM DJANGO FOR SEND FROM AJAX
return cookieValue;

//end function getCookie

function tag_filter()
var tag_filter = $("#tag_filter").val();
if(tag_filter == ''


now you need create a def for search with the parameter example:



from django.http import HttpResponse, JsonResponse

...
..
def SearchFilter(request):
filter = request.GET['tag_filter']
....
....
data =
'result':'ok_select'
'data': #your query

return JsonResponse(data, safe=False)


now you need declare this def on yours urls.py example:



from myapp.views import SearchFilter
urlpatterns = [
url(r'^search_filter', SearchFilter, name='search_filter'),
...
...
]


this is all... on the case of ajax this return success answer by console check this answer on the console from your web browser favorite..



and good luck..!!






share|improve this answer

























  • I'm working with class-based views, there's the main problem I'm having because I don't really know how the request is handled by the ListView class I'm inheriting from. I can't find a way to make the: filter = request.GET['tag_filter'] and get the dictionary from the JSON Everything you wrote helped though

    – amartini
    Nov 15 '18 at 22:28














0












0








0







I suggest use ajax, then your first step is implement ajax ...ajax is from Jquery then you need include the jquery on your template only for one file html or if your prefer in your base.html on the end of file before from your body end tag:



<!-- jQuery library -->
<script src="% static 'Jquery/jquery.min.js' %"></script>
....
...
all my files js
....
</body>
</html>


for download this jquery.min.js , please go to this link and save the file in to folder: static/Jquery/:



Link for download Jquery min.js



Don't forget save as jquery.min.js



The next is setup your settings.py for accept the static files:



STATIC_URL = '/static/'

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/static/',
]


the next is put the tag for load static files on the top of your file html or base.html as you wish:



% load staticfiles %
<!DOCTYPE html>
<html>
...
...
...
<!-- jQuery library -->
<script src="% static 'Jquery/jquery.min.js' %"></script>
....
...
all my files js
....
</body>
</html>


ok, now we include $.ajax first you need include on your button a function that recive your value from your input:



<input type="text" name="tag_filter" id ="tag_filter">
<button type="button" onclick="tag_filter()">Filter</button>


now your function tag_filter:



 function getCookie(name) 

var cookieValue = null;
if (document.cookie && document.cookie != '')
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++)
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '='))
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;



//RETURN YOUR TOKEN FROM DJANGO FOR SEND FROM AJAX
return cookieValue;

//end function getCookie

function tag_filter()
var tag_filter = $("#tag_filter").val();
if(tag_filter == ''


now you need create a def for search with the parameter example:



from django.http import HttpResponse, JsonResponse

...
..
def SearchFilter(request):
filter = request.GET['tag_filter']
....
....
data =
'result':'ok_select'
'data': #your query

return JsonResponse(data, safe=False)


now you need declare this def on yours urls.py example:



from myapp.views import SearchFilter
urlpatterns = [
url(r'^search_filter', SearchFilter, name='search_filter'),
...
...
]


this is all... on the case of ajax this return success answer by console check this answer on the console from your web browser favorite..



and good luck..!!






share|improve this answer















I suggest use ajax, then your first step is implement ajax ...ajax is from Jquery then you need include the jquery on your template only for one file html or if your prefer in your base.html on the end of file before from your body end tag:



<!-- jQuery library -->
<script src="% static 'Jquery/jquery.min.js' %"></script>
....
...
all my files js
....
</body>
</html>


for download this jquery.min.js , please go to this link and save the file in to folder: static/Jquery/:



Link for download Jquery min.js



Don't forget save as jquery.min.js



The next is setup your settings.py for accept the static files:



STATIC_URL = '/static/'

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/static/',
]


the next is put the tag for load static files on the top of your file html or base.html as you wish:



% load staticfiles %
<!DOCTYPE html>
<html>
...
...
...
<!-- jQuery library -->
<script src="% static 'Jquery/jquery.min.js' %"></script>
....
...
all my files js
....
</body>
</html>


ok, now we include $.ajax first you need include on your button a function that recive your value from your input:



<input type="text" name="tag_filter" id ="tag_filter">
<button type="button" onclick="tag_filter()">Filter</button>


now your function tag_filter:



 function getCookie(name) 

var cookieValue = null;
if (document.cookie && document.cookie != '')
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++)
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '='))
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;



//RETURN YOUR TOKEN FROM DJANGO FOR SEND FROM AJAX
return cookieValue;

//end function getCookie

function tag_filter()
var tag_filter = $("#tag_filter").val();
if(tag_filter == ''


now you need create a def for search with the parameter example:



from django.http import HttpResponse, JsonResponse

...
..
def SearchFilter(request):
filter = request.GET['tag_filter']
....
....
data =
'result':'ok_select'
'data': #your query

return JsonResponse(data, safe=False)


now you need declare this def on yours urls.py example:



from myapp.views import SearchFilter
urlpatterns = [
url(r'^search_filter', SearchFilter, name='search_filter'),
...
...
]


this is all... on the case of ajax this return success answer by console check this answer on the console from your web browser favorite..



and good luck..!!







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 18 '18 at 19:12









marc_s

582k13011231269




582k13011231269










answered Nov 15 '18 at 19:41









Diego AvilaDiego Avila

371212




371212












  • I'm working with class-based views, there's the main problem I'm having because I don't really know how the request is handled by the ListView class I'm inheriting from. I can't find a way to make the: filter = request.GET['tag_filter'] and get the dictionary from the JSON Everything you wrote helped though

    – amartini
    Nov 15 '18 at 22:28


















  • I'm working with class-based views, there's the main problem I'm having because I don't really know how the request is handled by the ListView class I'm inheriting from. I can't find a way to make the: filter = request.GET['tag_filter'] and get the dictionary from the JSON Everything you wrote helped though

    – amartini
    Nov 15 '18 at 22:28

















I'm working with class-based views, there's the main problem I'm having because I don't really know how the request is handled by the ListView class I'm inheriting from. I can't find a way to make the: filter = request.GET['tag_filter'] and get the dictionary from the JSON Everything you wrote helped though

– amartini
Nov 15 '18 at 22:28






I'm working with class-based views, there's the main problem I'm having because I don't really know how the request is handled by the ListView class I'm inheriting from. I can't find a way to make the: filter = request.GET['tag_filter'] and get the dictionary from the JSON Everything you wrote helped though

– amartini
Nov 15 '18 at 22:28




















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53323750%2fget-queryset-from-a-js-text-input%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

What does pagestruct do in Eviews?

Dutch intervention in Lombok and Karangasem

Channel Islands