Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I filter on request.user when using Django generic views?

I want to do something like this (from my urls.py), but I don't know if it's possible to get the user making the request:

    url(r'^jobs/(page(?P<page>[0-9]+)/)?$',
        object_list, {'queryset': Job.objects.filter(user=request.user), 
                      'template_name': 'shootmpi/molecule_list.html'},
        name='user_jobs'),
like image 783
Edward Dale Avatar asked Oct 08 '09 18:10

Edward Dale


People also ask

Should I use generic views Django?

The intention of Generic Views is to reduce boilerplate code when you repeatedly use similar code in several views. You should really use it just for that. Basically, just because django allows something you are doing generically you shouldn't do it, particularly not when your code becomes not to your like.

How do I filter records in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

What is the difference between GET and filter in Django?

The Difference between Django's filter() and get() methods are: get throws an error if there's no object matching the query. Basically use get() when you want to get a single unique object, and filter() when you want to get all objects that match your lookup parameters.


1 Answers

You can write a wrapper function that calls object_list with the required queryset.

In urls.py:

url(r'^(page(?P<page>[0-9]+)/)?$', 'views.user_jobs', name='user_jobs')

In views.py:

from django.views.generic.list_detail import object_list

def user_jobs(request, page):
    job_list=Job.objects.filter(user=request.user)
    return object_list(request, queryset=job_list,
        template_name='shootmpi/molecule_list.html',
        page=page)

There's a good blog post by James Bennett on using this technique.

like image 130
Alasdair Avatar answered Nov 15 '22 00:11

Alasdair