2012-09-13 221 views
0

我不能確定爲什麼驗證不在此註冊視圖中工作。我說因爲用戶正在進入數據庫,並且它正在重定向到下一個需要的頁面(它有一個login_required裝飾器),但是它會重定向回登錄頁面。 Authenticate使用給定的值返回shell中的新用戶。我也在這裏調試和粘貼:http://dpaste.org/J1HZ5 /出了什麼問題?驗證註冊頭痛

def register(request): 
    if request.method == 'POST': 
     form = UserCreationForm(request.POST) 
     if form.is_valid(): 
      new_user = form.save() 
      new_user = authenticate(username = request.POST['username'], 
            password = request.POST['password1']) 

      login(request, new_user) 
      context = RequestContext(request)  
      context['user_id'] = new_user.id 
      context['new_user'] = new_user 
      url = '/user/%s/' % new_user.id 
      return HttpResponseRedirect(url) 
    else: 
     form = UserCreationForm() 
    return render_to_response("registration/register.html", {'form': form}, 
           context_instance=RequestContext(request)) 

urls.py:

urlpatterns = patterns('', 
    # Examples: 
    url(r'^$', 'crewcal.views.index', name='home'), 
    # url(r'^ssc/', include('ssc.foo.urls')), 

    url(r'^events/(?P<event_id>\d+)/$', 'crewcal.views.event'), 
    url(r'^events/new/$', 'crewcal.views.new_event', name='new_event'), 
    url(r'^commit/$', 'crewcal.views.commit'), 
    url(r'^user/(?P<user_id>\d+)/$', user, name='user'), 
    url(r'^users/$', 'crewcal.views.users'), 

    url(r'^register/$', register, name='join'), 
    url(r'^login/$', 'django.contrib.auth.views.login'), 
    url(r'^logout/$', logout, {'next_page': '/'}, name='logout'), 
    url(r'^log_in/$', log_in, name='log_in'), 

    # Uncomment the admin/doc line below to enable admin documentation: 
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), 

    # Uncomment the next line to enable the admin: 
    url(r'^admin/', include(admin.site.urls)), 
) 

感謝

+0

用你的'urls.py'更新這個問題 –

+0

它現在在那裏。謝謝。 – KindOfGuy

回答

0

你安裝Django的會話中間件?

+0

默認情況下啓用會話中間件。 –

+0

是的,它是活動的。 – KindOfGuy

0

您可能想要發佈您的UserCreationForm代碼,但我注意到的一件事是您正在運行authenticate(...)調用,但並未實際檢查其結果並重定向。查看Django源代碼,有一個內置身份驗證表單(django.contrib.forms.AuthenticationForm),它驗證authenticate()調用的結果是否爲非,並且用戶處於活動狀態,如果不是,則會引發表單錯誤。

+0

的確如此。但爲什麼我應該這樣做?如果用戶創建表單正確驗證,那麼要驗證的用戶信息應該是新鮮和純淨的,並且肯定不會失敗。無論如何,我知道它是正確的(從數據庫和shell測試),但authenticate()沒有它。 PS。 UserCreationForm是默認值:'from django.contrib.auth.forms import UserCreationForm'。感謝您的關注。 – KindOfGuy

0

你的問題是這一行:

url(r'^user/(?P<user_id>\d+)/$', user, name='user'), 

確保user是一個有效的視圖。

+0

這是一個有效的觀點。當我獨立於寄存器進行調用時,它可以工作。我的問題是(調試了這個),一旦註冊完成,它會重定向到一個用戶頁面,然後@login_required裝飾器再次重定向到登錄。如果我刪除了login_decorator,則後登記重定向會將我留在用戶頁面上,這意味着登錄在登錄時沒有正確發生。 – KindOfGuy

0

您的密碼字段是password1還是password

def register(request): 
    if request.method == 'POST': 
     form = UserCreationForm(request.POST) 
     if form.is_valid(): 
      new_user = form.save() 
      new_user = authenticate(username = request.POST['username'], 
            password = request.POST['password1']) # here? 

      login(request, new_user) 
      # rest of the code...