0

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 UserInfoFormthat 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.

  • 1
    In your method you may only need an `obj.save()`. But in the broader scope, is there a reason you aren't just using `form.save()`? – FamousJameous Jun 26 '17 at 19:26
  • @FamousJameous form.save is creating duplicates. But I dont want more than one person with the same email id in the database. – Nikhil Rath Jun 26 '17 at 20:19
  • I think the convention is to have different forms for create vs update. For the update case, you pass in the existing instance to the form constructor before sending to the client (so that the form fields are populated with the existing data). Then when the form is posted you again pass in the instance (usually obtained via the ID in the URL). Then, when you call `form.save()` it just updates the existing instance. See https://stackoverflow.com/a/10205988/3901060 for more information. – FamousJameous Jun 26 '17 at 21:06
  • @FamousJameous ok, I'll try that. Thanks for the help – Nikhil Rath Jun 27 '17 at 05:06

0 Answers0