Search code examples
pythondjangopostgetdjango-generic-views

Generic views request handling Django


I'm relative new in Django. I want to use generic views like this :

class photogalleryView(generic.ListView):
    template_name = 'xxx/photogallery.html'
    model = Foto
    query = Foto.objects.all()

def get_queryset(self):
    return self.query

and I definitelly don't know how to handle GET or POST request or something like $_SESSION like in PHP, can you please give me some pieces of advice please ? Thank you very much guys !

for example - I want to handle GET request on this URL:

http://127.0.0.1:8000/photogallery?filter=smth

Solution

  • First, returning the same QuerySet object query = Foto.objects.all() doesn't make much sense and can (and will) get you into trouble when you try to use filters and pagination. If you want to modify your QuerySet manually, do the following:

    def get_queryset(self, *args, **kwargs):
        qs = super().get_queryset(*args, **kwargs)
        # modify the qs QuerySet in the way you want
        return qs
    

    In Django, you don't normally use GET or POST. Django handles it for you :) The example of what you want to achieve is here: https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-display/#dynamic-filtering

    In fact, Django documentation is very nice and comprehensive, at least for the public features. Pay your attention on the url(r'^books/([\w-]+)/$', PublisherBookList.as_view()), in the example, where ([\w-]+) RegEx group captures some argument (e.g. "smith") which you can later use in your get_queryset method (as self.args[0] in the example).

    To understand more about url patterns, read this piece of the documentation: https://docs.djangoproject.com/en/1.10/topics/http/urls/#named-groups