2015-02-05 93 views
2

我在嘗試訪問Django中的PasswordChangeView時遇到TypeError。錯誤是:如何將參數傳遞給Django的PasswordChangeForm的__init__函數

Django Version: 1.7.3 
Exception Type: TypeError 
Exception Value:  
__init__() missing 1 required positional argument: 'user' 
Exception Location: /usr/local/lib/python3.4/dist-packages/django/views/generic/edit.py in get_form, line 45 
Python Executable: /usr/bin/python3.4 

我一直沒能找到FormView控件的例子從https://docs.djangoproject.com/en/1.7/_modules/django/contrib/auth/forms/#PasswordChangeForm

加載提供PasswordChangeForm這是我想做到這一點,但我仍然在運行到錯誤即使經過一些調整。

urls.py

url(r'^password/change/$', login_required(views.PasswordChangeView.as_view()), name='change_password'), 

views.py

class PasswordChangeView(FormView): 
    template_name = 'change_password.html' 
    form_class = PasswordChangeForm 

    def dispatch(self, request, *args, **kwargs): 
     try: 
      self.initial['user'] = self.request.user 
     except AttributeError: 
      raise Http404 

     return super(PasswordChangeView, self).dispatch(request, *args, **kwargs) 

我不能肯定爲什麼我仍然得到這個錯誤。如果我看看,我和FormView控件延長FormMixin我看到以下內容:

def get_form(self, form_class): 
    """ 
    Returns an instance of the form to be used in this view. 
    """ 
    return form_class(**self.get_form_kwargs()) 

def get_form_kwargs(self): 
    """ 
    Returns the keyword arguments for instantiating the form. 
    """ 
    kwargs = { 
     'initial': self.get_initial(), 
     'prefix': self.get_prefix(), 
    } 

    if self.request.method in ('POST', 'PUT'): 
     kwargs.update({ 
      'data': self.request.POST, 
      'files': self.request.FILES, 
     }) 
    return kwargs 

和...

def get_initial(self): 
    """ 
    Returns the initial data to use for forms on this view. 
    """ 
    return self.initial.copy() 

來源:https://github.com/django/django/blob/master/django/views/generic/edit.py

我證實,self.initial包含用戶通過調用self.get_form_kwargs():

{'initial': {'user': <SimpleLazyObject: <User: maaack>>}, 'prefix': None} 

我還該怎麼樣o將用戶轉到表單中?

回答

5

您應該將用戶作爲第一個參數傳遞給窗體構造函數。看看SetPasswordForm.__init__()

def get_form(self, form_class): 
    return form_class(self.request.user, **self.get_form_kwargs()) 

有一個在PasswordChangeForm沒有user字段,以便在initialuser關鍵是沒用的。

+0

謝謝!這很容易理解。 – Maaack

+0

我希望我能多點讚賞。 – n3storm