2013-07-09 82 views
1

我使用Django和試圖建立一個登記表,下面是我的代碼對象是不可調用的錯誤

forms.py

from django import forms 

attrs_dict = { 'class': 'required' } 

class RegistrationForm(forms.Form): 
    username = forms.RegexField(regex=r'^\w+$', 
           max_length=30, 
           widget=forms.TextInput(attrs=attrs_dict), 
           label=_(u'username')) 
    email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,maxlength=75)), 
           label=_(u'email address')) 
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), 
           label=_(u'password')) 
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), 
           label=_(u'password (again)')) 

views.py

from authentication.forms import RegistrationForm 

def register(request): 
    regsiter_form = RegistrationForm() 
    if request.method=='POST': 
     form = regsiter_form(request.POST) 
     if form.is_valid(): 
      new_user = User.objects.create_user(username=request.POST['username'], 
               email=request.POST['email'], 
               password=request.POST['password1']) 
      new_user.is_active = False 
      new_user.save() 
      return HttpResponseRedirect(reverse('index')) 
    return render_to_response('registration/registration_form.html'{'form':regsiter_form}) 

所以當我們去到URL,登記表顯示的是,當我們進入德泰LS並點擊提交我收到以下錯誤

TypeError at /accounts_register/register/ 
'RegistrationForm' object is not callable 
Request Method: POST 
Request URL: http://localhost:8000/accounts_register/register/ 
Django Version: 1.5.1 
Exception Type: TypeError 
Exception Value:  
'RegistrationForm' object is not callable 

回溯

▶ Local vars 
/home/user/package/authentication/views.py in register 
     form = regsiter_form(request.POST) 

所以,任何人都可以請讓我知道爲什麼上面的表格對象被抱怨的對象是不可調用的,而且我們需要進行更改才能避免此錯誤。

回答

2

它應該是:

def register(request): 
    regsiter_form = RegistrationForm() 
    if request.method=='POST': 
     form = RegistraionForm(request.POST) 
     if form.is_valid(): 
      new_user = User.objects.create_user(username=request.POST['username'], 
              email=request.POST['email'], 
              password=request.POST['password1']) 
      new_user.is_active = False 
      new_user.save() 
      return HttpResponseRedirect(reverse('index')) 
    return render_to_response('registration/registration_form.html'{'form':regsiter_form}) 

所以,form = regsiter_form(request.POST)應該是form = RegistrationForm(request.POST)你的POST檢查裏面。

的一點是你第一次使用regsiter_form = RegistrationForm()創建RegistrationForm的對象/實例,然後你試過regsiter_form(request.POST),所以基本上你想,除非有上定義的__call__方法再次調用對象/實例,它是不允許你類。

2

代替

form = regsiter_form(request.POST) 

regsiter_form = RegistrationForm(request.POST) 

而且使用register_form對象,而不是form

此外,使用數據從form.cleaned_data創建用戶對象,而不是從request.POST

作爲

new_user = User.objects.create_user(username=form.cleaned_data['username'] ...) 
相關問題