2014-03-25 28 views
2

我正在經歷django-registrationsource code。這是一個定義的基於類的視圖。我很難理解get_success_url是如何工作的? 從documentationget_sucess_url如何在django中工作?

get_success_url() 
    Determine the URL to redirect to when the form is successfully validated. 
Returnsdjango.views.generic.edit.ModelFormMixin.success_url if it is provided; 
otherwise, attempts to use the get_absolute_url() of the object. 

但這是如何工作在下面的示例代碼: 爲什麼是two arguments empty?他們應該採取什麼?

class ActivationView(BaseActivationView): 
    def activate(self, request, activation_key): 
     """ 
     Given an an activation key, look up and activate the user 
     account corresponding to that key (if possible). 

     After successful activation, the signal 
     ``registration.signals.user_activated`` will be sent, with the 
     newly activated ``User`` as the keyword argument ``user`` and 
     the class of this backend as the sender. 

     """ 
     activated_user = RegistrationProfile.objects.activate_user(activation_key) 
     if activated_user: 
      signals.user_activated.send(sender=self.__class__, 
             user=activated_user, 
             request=request) 
     return activated_user 

    def get_success_url(self, request, user): 
     return ('registration_activation_complete',(), {}) 

回答

2

這三個參數傳遞給Django的reverse URL lookup,特別是django.core.urlresolvers.reverse功能。 ()(空元組)給出位置參數,{}(空字典)給出關鍵字參數。那麼,最終被傳遞的是:

reverse('registration_activation_complete', args=(), kwargs={}) 

您可以在urls.py文件的URL registration_activation_complete不帶參數見(網址只是activate/complete/$),這就是爲什麼那些都是空的。

+0

如果我是正確的,只有當表單被成功驗證時才調用get_success_url。所以當它未被驗證時被調用?有沒有'get_failure_url'? – eagertoLearn

+0

@eagertoLearn:如果表單未被成功驗證,它會默認執行Django中無效的表單(回到表單頁面,並在表單中添加一些錯誤消息)。如果你想定製它,你可以實現一個'form_invalid'方法(參見[這裏](https://docs.djangoproject.com/en/1.5/ref/class-based-views/mixins-editing/))。如果你願意的話,該方法可以返回一個HttpResponseRedirect到一個新的URL(儘管目前還不清楚爲什麼你會 - 當某人註冊失敗時你通常不會將它們發送到*新頁面) –

+0

謝謝!我一直試圖傳遞一個不同的'url'到'get_success_url',這將需要參數,我在這裏以不同的方式發佈了參數。看起來這不是微不足道的(至少對我來說)。 https://stackoverflow.com/questions/22622738/how-to-pass-account-information-to-django-template-in-django-registration – eagertoLearn