简体   繁体   中英

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

Have a look at the documentation for class based views, if that's what you want to use.

You can add get and post methods to your class, and they will trigger on each respective request.

These methods take a request argument, which can be used to access data from the client, the session, and the logged in user. Check out the docs for details.

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 (eg "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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM