我有一个名为UserInfo
的模型。
class UserInfo(models.Model):
username = models.CharField(max_length=240 , default = "" , blank = False , null = False)
first_name = models.CharField(max_length=240 , default = "" , blank = False , null = False)
last_name = models.CharField(max_length=240 , default="" , blank = False , null = False)
address = models.CharField(max_length=500 , default="" , blank = False , null = False)
email = models.CharField(max_length=240 , default="" , blank = False , null = False)
phoneNumber = models.CharField(max_length=240 , default="" , blank = False , null = False)
pincode = models.CharField(max_length=240 , default="" , blank = False , null = False)
我还有UserInfoForm
这些字段。
class UserInfoForm(forms.ModelForm):
class Meta:
model = UserInfo
fields = []
for field in UserInfo._meta.get_fields(): #automatically update fields from userinfo model
fields.append(field.name)
exclude = ['username']
想要的是迭代在UserInfo
模型的字段上,并使用UserInfoForm
中的数据进行更新,而不是将其全部硬编码。
我试过这个:
obj = UserInfo.objects.get(email = request.user.email)
if obj.username == request.user.username: #basically a test to see if the same person is updating his profile, or is someone else using this email id
for field in UserInfo._meta.get_fields():
fieldname = field.name
fieldvalue = form.cleaned_data.get(fieldname)
obj.field = fieldvalue #doesn't work
obj.save()
但这不起作用。此代码完全没有显示错误,但数据库仍未更新。请建议一种方法,以便我可以为用户更新信息,迭代字段。