Python Django表格';int';对象没有属性';必需的';对于在函数中添加的字段
在Django 1.6和crispy表单中,我试图添加Python Django表格';int';对象没有属性';必需的';对于在函数中添加的字段,python,django,django-crispy-forms,Python,Django,Django Crispy Forms,在Django 1.6和crispy表单中,我试图添加forum\u id\u number,这是用户提交后从API调用返回的。然而,我得到了一份工作 Exception Value: 'int' object has no attribute 'required' 在我提交表格之后。我已经验证了self.fields['forum\u id\u number']=response[“User”][“id”]是导致此问题的原因 self.fields['forum\u id\u n
forum\u id\u number
,这是用户提交后从API调用返回的。然而,我得到了一份工作
Exception Value:
'int' object has no attribute 'required'
在我提交表格之后。我已经验证了self.fields['forum\u id\u number']=response[“User”][“id”]
是导致此问题的原因
self.fields['forum\u id\u number']
是forms.Field
子类的一个实例。它描述了属性self.forum\u id\u number
。行self.fields['forum\u id\u number']=response[“User”][“id”]
覆盖此字段描述,并将其设置为(大?)整数对象的实例。当然,此实例没有属性必需
设置论坛id\u编号
值的“正确”方法是使用self.forum\u id\u编号=响应[“用户”][“id”]
或self.cleanned\u数据[“论坛id\u编号”]=响应[“用户”][“id”]
Correct在引号中,因为在这种情况下,它实际上不是正确的方式。无法知道是否在任何clean\u field
方法中清理了字段forum\u id\u number
,因此您不知道是否应该设置self.forum\u id\u number
或self.cleaned\u data['forum\u id\u number']
。现在在论坛id\u编号
的情况下,没有安全问题,但是任何有Firebug或类似东西的人都可以更改用户分配的值
。通常最好从表单中排除隐藏字段,并在表单的save
方法中设置实例本身的值。当然,您不能在save
方法中引发ValidationError
(当然,您可以,但它会产生500内部服务器错误
),因此您必须在clean\u论坛\u用户名
方法中获取用户id:
class AccountForm(forms.ModelForm):
....
def clean_forum_username(self):
data = self.cleaned_data['forum_username']
SLUG = "users/" + data + ".json"
status_code, response = do_request(SLUG)
if status_code != 200:
raise forms.ValidationError("Your username was not"
" found! Please check the"
" the spelling. Also, your"
" forum username is your"
" forum sign in name.")
elif status_code == 200:
self.response = response
return data
def save(self, *args, **kwargs):
# self.response should be valid, otherwise a `ValidationError` would've been raised
self.instance.forum_id_number = self.response['User']['Id']
return super(AccountForm, self).save(*args, **kwargs)
class Employee(models.Model):
user_assigned = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='r_assigned')
irc_name = models.CharField(max_length="25",
unique=True)
forum_id_number = models.BigIntegerField(unique=True)
forum_username = models.CharField(max_length="50",
unique=True)
def __unicode__(self):
return self.irc_name
class AccountForm(forms.ModelForm):
....
def clean_forum_username(self):
data = self.cleaned_data['forum_username']
SLUG = "users/" + data + ".json"
status_code, response = do_request(SLUG)
if status_code != 200:
raise forms.ValidationError("Your username was not"
" found! Please check the"
" the spelling. Also, your"
" forum username is your"
" forum sign in name.")
elif status_code == 200:
self.response = response
return data
def save(self, *args, **kwargs):
# self.response should be valid, otherwise a `ValidationError` would've been raised
self.instance.forum_id_number = self.response['User']['Id']
return super(AccountForm, self).save(*args, **kwargs)