2012-08-26 11 views
5

Estoy tratando de seguir el [Django Tutorial 6] [1] para hacer la autenticación del usuario. Pero me quedo atascado. Obtengo este error de atributo: el objeto Unicode 'no tiene atributo' get '. Los modelos, vista y formularios se proporcionan a continuación. No sabe dónde está el error ... ¿Necesita un poco de ayuda ...el objeto unicode 'no tiene ningún atributo' get 'en Django

models.py

from django.db import models 
from django.contrib.auth.models import User 

class Drinker(models.Model): 

    user = models.OneToOneField(User) 
    birthday = models.DateField() 
    name = models.CharField(max_length=100) 

    def __unicode__(self): 
     return self.name 

views.py

from django.http import HttpResponseRedirect 
from django.shortcuts import render_to_response 
from django.template import RequestContext 
from drinker.forms import RegistrationForm 
from django.contrib.auth.models import User 
from drinker.models import Drinker 


def DrinkerRegistration(request): 
    if request.POST: 
     form =RegistrationForm(request.POST) 
     if form.is_valid(): 
      user = User.objects.create_user(username=form.cleaned_data['username'],email=form.cleaned_data['email']) 
      password = form.cleaned_data['password'] 
      user.save() 
      drinker=Drinker(user=user,name=form.cleaned_data['name'],birthday=form.cleaned_data['birthday']) 
      drinker.save() 
      return HttpResponseRedirect('/profile/') 
     else: 
      return render_to_response('register.html',{'form':form,},context_instance=RequestContext(request)) 
    else: 
     form = RegistrationForm() 
     return render_to_response('register.html',{'form':form,},context_instance=RequestContext(request)) 

forms.py

from django import forms 
from django.contrib.auth.models import User 
from django.forms import ModelForm 
from drinker.models import Drinker 

class RegistrationForm(ModelForm): 
    username = forms.CharField(label=(u'User Name')) 
    email = forms.EmailField(label =(u'Email Address')) 
    password = forms.CharField(label =(u'Password'),widget=forms.PasswordInput(render_value=False)) 
    password1 = forms.CharField(label =(u'Verify Password'),widget=forms.PasswordInput(render_value=False)) 

    class Meta: 
     model = Drinker 
     exclude = ('user',) 

    def clean_username(self): 
     username = self.cleaned_data['username'] 
     try: 
      User.objects.get(username=username) 
     except User.DoesNotExist: 
      return username 
     raise forms.ValidationError("That username is already taken. Please select another") 
    def clean(self): 
     password = self.cleaned_data['password'] 
     password1= self.cleaned_data['password1'] 
     if password and password1 and password != password1: 
      raise forms.ValidationError("The passwords did not match. Please try again") 
     return password 

de error :

Environment: 


Request Method: POST 

Django Version: 1.4 
Python Version: 2.7.1 
Installed Applications: 
('django.contrib.auth', 
'django.contrib.contenttypes', 
'django.contrib.sessions', 
'django.contrib.sites', 
'django.contrib.messages', 
'django.contrib.staticfiles', 
'django.contrib.admin', 
'django.contrib.admindocs', 
'drinker') 
Installed Middleware: 
('django.middleware.common.CommonMiddleware', 
'django.contrib.sessions.middleware.SessionMiddleware', 
'django.middleware.csrf.CsrfViewMiddleware', 
'django.contrib.auth.middleware.AuthenticationMiddleware', 
'django.contrib.messages.middleware.MessageMiddleware') 


Traceback: 
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 
    111.       response = callback(request, *callback_args, **callback_kwargs) 
File "/Users/cnnlakshmen_2000/Projects/Permissions/drinker/views.py" in DrinkerRegistration 
    12.  if form.is_valid(): 
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/forms/forms.py" in is_valid 
    124.   return self.is_bound and not bool(self.errors) 
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/forms/forms.py" in _get_errors 
    115.    self.full_clean() 
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/forms/forms.py" in full_clean 
    272.   self._post_clean() 
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/forms/models.py" in _post_clean 
    311.   exclude = self._get_validation_exclusions() 
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/forms/models.py" in _get_validation_exclusions 
    297.     field_value = self.cleaned_data.get(field, None) 

Exception Type: AttributeError at /register/ 
Exception Value: 'unicode' object has no attribute 'get' 
+0

¿Dónde está el error? ¿Tienes retroceder? – Rohan

+0

Actualiza tu pregunta con el rastreo completo. –

Respuesta

7

Usted está devolviendo password del método clean(), en lugar de self.cleaned_data.

+0

¿Puedes explicar por qué debería ser self.cleaned_data? no contraseña? felizmente lo puse en funcionamiento, pero mirando hacia atrás no entiendo por qué es tan ... – lakesh

+2

Porque 'clean' es el método de validación general para todo el formulario, por lo que debe devolver todos los datos del formulario. –

+0

gracias ... si se trata de la función clean_password, entonces puedo devolver la contraseña solo ¿no? ¿o todavía tengo que pasar los datos limpios en ese caso también? – lakesh

Cuestiones relacionadas