Saturday, February 24, 2018

Simple Search Feature

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.

No comments:

Post a Comment