Sunday, February 25, 2018

Re: Simple Search Feature

I would do something simitar to:

class SongListView(ListView):
model = Song
context_object_name = 'songs'
template_name = 'songs/song_list.html'

def get_queryset(self):
qs = super().get_queryset()
name = self.request.get("name")
if name:
qs = qs.filter(name__icontains=name)
return qs

El dom, feb 25 2018 a las 09:17:07 , tango ward <tangoward15@gmail.com>
escribió:
> Hi,
>
> I am playing around on adding a search feature to a website. I am currently
> encountering a problem when the page should load a list of songs and after
> typing in a song title in the search box:
>
>
> views.py
>
> class SongListView(ListView):
> model = Song
> context_object_name = 'songs'
> template_name = 'songs/song_list.html'
>
> def get(self, request, *args, **kwargs):
>
> if request.method == 'GET':
> song_name = request.GET.get('name', "Error")
> songs = self.model.objects.filter(name__icontains=song_name)
> else:
> songs = self.models.all()
> return render(request, self.template_name, {'songs': songs})
>
> problem is when I click the search button with the text box empty, I am
> getting the list of all the song (url: /songs/?name=) but if I just load
> the page wihout clicking the submit button (url: /songs/), it doesn't give
> me the list all the songs. The search box works if I type the correct song
> name as it shows the song title. Problem is the page should load all the
> songs before I search a particular song.
>
> Any suggestions so I can enhance my code?
>
>
> Thanks,
> Jarvis
>
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAA6wQLJ5bnMzR1etSRY191KL3fWkMpPsvhKnFBKtAuc1iLNKFg%40mail.gmail.com.
> For more options, visit https://groups.google.com/d/optout.

--
José Sánchez Moreno <jose@o2w.es>
O2W Leading Software - www.o2w.es
C/ Trovero Marin, 5 30730 San Javier (Murcia)
Tlf: 968 192 905 - 656 817 548
Condiciones Legales de este e-mail en: http://www.o2w.es/email

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/87h8q5h1v7.fsf%40o2w.es.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment