Generic Views with flair?

27 views
Skip to first unread message

Lachlan Musicman

unread,
May 6, 2012, 6:57:50 PM5/6/12
to Django users
I've happily worked out how to work @login_required for entries in
views.py, but since the latest tutorial (which I followed) recommends
moving to the Generic Views my code is now like this:

urls.py

...
url(r'^people/$',
ListView.as_view(
queryset=Person.objects.all())),

url(r'^person/(?P<pk>\d+)/$',
DetailView.as_view(
model=Person)),
...

How would I set the @login_required for these? Do I have to go back to
writing them up in views.py for this functionality?

Further, the Person model is FK'd to a bunch of other traits like
Certificates, (Work) Experience and Qualifications. They come up fine
in the admin interface, using inlines. I read in the docs that there
are some extra Generic Views so I've added a CreateView and an
UpdateView to my urls.py

url(r'^person/add/$',
CreateView.as_view(
#model=Person)),
template_name='ner/person_create.html',
form_class=PersonForm)),

url(r'^person/(?P<pk>\d+)/edit/$',
UpdateView.as_view(
model=Person)),

But now I'm uncertain how I can include the extra traits within these
two functions - they don't appear by default, I'm just getting the raw
Person model. I would like to have it like I can in the admin
interface via the Inlines?


Cheers
L.

Daniel Sokolowski

unread,
May 7, 2012, 11:09:50 AM5/7/12
to Django users
For your first question you can:

url(r'^people/$',
login_required(ListView.as_view(
queryset=Person.objects.all()))),

or in your view decorate the dispatch method:

@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(ProtectedView, self).dispatch(*args, **kwargs)

See:
https://docs.djangoproject.com/en/dev/topics/class-based-views/#decorating-class-based-views

For the second question I can only suggest you look into overriding the
default ModelForm of the view and using that. The docs are a still little
lacking but see
https://docs.djangoproject.com/en/dev/ref/class-based-views/#editing-mixins
and also take a look at the code itself
https://github.com/django/django/blob/master/django/views/generic/edit.py.
Doing the latter part thought me a lot about using class based views.
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to
django-users...@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.


Daniel Sokolowski
Web Engineer
KL Insight
http://klinsight.com/ or http://webdesign.danols.com

sbrandt

unread,
May 9, 2012, 8:59:53 AM5/9/12
to Django users
There is another way: Class Based View decorators:
http://djangosnippets.org/snippets/2668/
Reply all
Reply to author
Forward
0 new messages