2015-09-07 187 views
0

我有一個表單保存的問題。我有一個名爲UserProfile模型,就像這樣:__init __()得到了一個意外的關鍵字參數'last_name'

class UserProfile(models.Model): 
    first_name = models.CharField(max_length=50) 
    last_name = models.CharField(max_length=75) 
    email = models.EmailField(max_length=50, unique=True) 
    password = models.CharField(max_length=16) 
    age = models.IntegerField() 
    ... 

和形式創建模型的實例,就像這樣:

class UserProfileForm(forms.Form): 
    first_name = forms.CharField(label='Introduzca su nombre', max_length=50) 
    last_name = forms.CharField(label='Introduzca sus apellidos', max_length=75) 
    email = forms.EmailField(label='Introduzca su email', max_length=50) 
    birth_date = forms.DateField(label='Introduzca su fecha de nacimiento', widget=forms.DateTimeInput(format='%d/%m/%Y')) 
    password = forms.CharField(label='Introduzca su contrasena', max_length=16, widget=forms.PasswordInput()) 
    password_repeat = forms.CharField(label='Por favor, repita su contrasena', max_length=16, widget=forms.PasswordInput()) 
    ... 
    def save(self): 
     age = (date.today()-self.cleaned_data['birth_date']).days/365 
     user = UserProfile(first_name=self.cleaned_data['first_name'], 
         last_name=self.cleaned_data['last_name'], 
         email=self.cleaned_data['email'], 
         password=self.cleaned_data['password'], 
         age=age) # The error is detected in this line 
     user.save() 
     return user 

它引發以下錯誤行:

__init__() got an unexpected keyword argument 'last_name' 

我不知道有什麼問題,誰能幫助我?

+1

這是Django?你確定'UserProfile'類與你所顯示的一樣嗎? – warvariuc

+0

您在UserProfile中的構造函數只接受一個參數(model,Model)不是5!這就是爲什麼解釋者尖叫'last_name'的原因。更改您在UserProfile中傳遞的參數或創建模型,並添加像「first_name」,「last_name」這樣的東西來建模對象,並將此對象傳遞給構造函數。 – pkruk

+0

@pkruk你從哪裏得到這個信息? 「[*關鍵字參數只是您在模型中定義的字段的名稱。*](https://docs.djangoproject.com/en/1.8/ref/models/instances/#django.db.models 。模型)」。該錯誤似乎沒有在代碼中顯示。 – dhke

回答

4
class UserProfile(models.Model): 
    first_name = models.CharField(max_length=50) 
    last_name = models.CharField(max_length=75) 
    email = models.EmailField(max_length=50, unique=True) 
    password = models.CharField(max_length=16) 
    age = models.IntegerField() 
    ... 

我想你在這裏有__init__方法,你沒有顯示。如果您使用的是它應該是這樣的:

def __init__(self, *args, **kwargs): 
     ... # your code here 
     super(UserProfile, self).__init__(*args, **kwargs) 
     ... # and/or here 

換句話說,你已經在方式,它的簽名不匹配母公司實現的簽名覆蓋__init__

+0

謝謝warvariuc;)我解決了它,我從我的所有模型中刪除了所有的__init__方法,它的工作原理 –

相關問題