I have a model named 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)
I also have a UserInfoForm
that has these fields.
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']
What is want is to iterate over the fields of UserInfo
model and update with data in UserInfoForm
, rather than hardcoding it all.
I have tried this:
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()
But this doesn't work. This code shows no errors at all but still the database isn't updated. Please suggest a method so I can update information for a user, iterating over the fields.