Django Contrib Auth + Class Based Generic Views

391 views
Skip to first unread message

Matheus Ashton

unread,
Apr 2, 2012, 11:01:41 PM4/2/12
to django...@googlegroups.com
Hello Everybody,

I'm having a problem using the django.contrib.auth app and class based generic views in Django 1.3 / 1.4:

After submitting the login form, my view receives the post data and tries to authenticate the user and then redirect to a success page. Ok nothing new..
The problem is: My HomeView wich extends the TemplateView, receive the redirect from the login form and uses a render_to_response function to render the template, and that is my problem, because render_to_response does not create a RequestContext object, the one I need to show the newly authenticated user data, because that is a requirement for django.contrib.auth app, if the request is not a RequestContext, the authenticated user data, is not passed to the template (https://docs.djangoproject.com/en/1.4/topics/auth/#authentication-data-in-templates)..

Does someone can help me with this problem?

PS: Sorry about my English, it is not my first language

Thanks :D

Sergiy Khohlov

unread,
Apr 3, 2012, 4:26:31 AM4/3/12
to django...@googlegroups.com
Please provide your urls.py and your view which is used for this ....

2012/4/3 Matheus Ashton <matheu...@gmail.com>:

> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/django-users/-/ywPX8VH5CUQJ.
> 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.

Matheus Ashton

unread,
Apr 3, 2012, 11:02:30 PM4/3/12
to django...@googlegroups.com
urls.py:

urlpatterns = patterns('',
    url(r'^/login$', LoginView.as_view()),
    url(r'^$', HomeView.as_view(), {}, 'home'),
)

settings.py:

  LOGIN_URL='/login/'

views.py:

class LoginView(FormView):
  form_class = LoginForm
  template_name = "auth/form.html"
  
  def post(self, request, *args, **kwargs):
    form = self.get_form(self.get_form_class()) 
    if form.is_valid():
      user = self.request['login']
      password = self.request['password']
      try:
        auth = Authenticator()
        auth.authenticate(user, password, self.request)
        return self.form_valid(form)
  def get_success_url(self):
    return reverse('home')

class HomeView(TemplateView):
   template_name = 'user/home.html'


components.py: 

class Authenticator():
  def authenticate(self, user, password, request = None):
    self.user = auth.authenticate(username=user, password=password)
    if request:
      return self.login(request)
    
    return self.user
  
  def login(self, request):
    if self.user is not None:
      if self.user.is_active:
        auth.login(request, self.user)
        return self.user
      else:
        raise UserDisabledException("Usuario inativo")
    else:
      raise InvalidLoginException("Usuario/Senha invalidos")
           
class UserDisabledException(Exception):
  def __init__(self, value):
    self.value = value
    
  def __str__(self):
    return repr(self.value)
  
class InvalidLoginException(Exception):
  def __init__(self, value):
    self.value = value
    
  def __str__(self):
    return repr(self.value)


Thanks again :)

2012/4/3 Sergiy Khohlov <skho...@gmail.com>

Sergiy Khohlov

unread,
Apr 4, 2012, 5:14:18 AM4/4/12
to django...@googlegroups.com
So much code .....
Ok, lets start

2012/4/4 Matheus Ashton <matheu...@gmail.com>:


> urls.py:
>
> urlpatterns = patterns('',
>     url(r'^/login$', LoginView.as_view()),
>     url(r'^$', HomeView.as_view(), {}, 'home'),
> )
>

More simple way is using decorator for checking if user is authorized.

Add next string to your urls.py

# import decorator functionality
from django.contrib.auth.decorators import login_required

# import your views

from home.views import HomeView

final urls.py is :


from django.conf.urls.defaults import patterns, include, url
from django.contrib.auth.decorators import login_required
from home.views import HomeView

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
(r'^login/', 'django.contrib.auth.views.login', {'template_name':
'login.html'}),
(r'^$', login_required(HomeView.as_view())),
)

First line is mean that default djano auth mechanism is used for
checking user's auth.
Socond line means : each request is passed to HomeView but should
be authorized. If user is not authorized then redirect to login
windows should be .


As result your views.py should be :

from django.views.generic import TemplateView
# Create your views here.
class HomeView(TemplateView):
template_name='home.html'

Only three lines of the code !
You dont need more!


Thanks,
Serge

Javier Guerra Giraldez

unread,
Apr 4, 2012, 7:44:35 AM4/4/12
to django...@googlegroups.com
On Wed, Apr 4, 2012 at 4:14 AM, Sergiy Khohlov <skho...@gmail.com> wrote:
> As result  your views.py should be :
>
> from django.views.generic import TemplateView
> # Create your views here.
> class HomeView(TemplateView):
>    template_name='home.html'
>
>  Only three lines of the code !
> You dont  need more!

if in urls.py you replace

(r'^$', login_required(HomeView.as_view())),

with
(r'^$', login_required(TemplateView(template_name='home.html').as_view())),


you don't need any HomeView class!


--
Javier

Sergiy Khohlov

unread,
Apr 4, 2012, 9:25:47 AM4/4/12
to django...@googlegroups.com
Sound good!
Usually project is not so simple (only url.py + settings.py)

2012/4/4 Javier Guerra Giraldez <jav...@guerrag.com>:

Matheus Ashton

unread,
Apr 4, 2012, 5:30:08 PM4/4/12
to django...@googlegroups.com
Ok, Thanks for the advices :) but I still have the original problem, when i access the HomeView the template is rendered with a render_to_response view, with a simple Context object and not a RequestContext object, because of that I do not have the authenticated user data in my template...

2012/4/4 Sergiy Khohlov <skho...@gmail.com>

Sergiy Khohlov

unread,
Apr 5, 2012, 2:20:19 AM4/5/12
to django...@googlegroups.com
As I understand you would like to send some values to the templates ?
Are you eould like to check if user is authenticated ?
I 've understand near to nothing from your last message.


2012/4/5 Matheus Ashton <matheu...@gmail.com>:

Reply all
Reply to author
Forward
0 new messages