swedishfished swedishfished - 7 months ago 13
Python Question

Updating Field in Django does not work

I have the following in my views.py

if request.method=='POST':
form = ExtraForm(request.POST,instance=request.user)
print ("hi")
if form.is_valid():
form.save()
print ("yes")
print ("newform is ")
else:
form = ExtraForm(instance=request.user)
context['form']=form
return render(request, "updateProfile.html",context)


Now what happens is that I get no errors and it does everything perfectly fine but it does NOT end up updating anything!! Which does not make sense to me. Any idea what is going on?

ExtraForm:

class ExtraForm(forms.ModelForm):
research_place = forms.CharField(max_length=256, label="", required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'First Name','required':True}))
studies = forms.CharField(max_length=256, label="", required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'Last Name','required':True}))

class Meta:
model = RegisterUser
fields = ['research_place','studies']
widgets = {
# 'image': ImageCropWidget,
}


Models:

class RegisterUser(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)

biography = models.CharField(max_length=1000000,blank=True)
research_place = models.CharField(max_length=1000000,blank=True)
studies = models.CharField(max_length=1000000,blank=True)

image = models.ImageField(blank=True,null=True,upload_to='uploaded_images',default ="uploaded_images/defaultReal.jpg")
# cropping = ImageRatioField('image','200x200',size_warning=True) #width x height

avatar_thumbnail = ImageSpecField(source='image',
processors=[ResizeToFill(200, 200)],
format='JPEG',
options={'quality': 60})

activation_key = models.CharField(max_length=50)
key_expires = models.DateTimeField()
class Meta:
permissions = (
("has_uploaded", ("Has uploaded")),
("is_authenticated", ("Is authenticated")),
)

Answer

It looks like the form is not valid at all. Add an else clause and check for errors:

if request.method == "POST":
    form = ExtraForm(request.POST, instance=request.user)
    if form.is_valid():
        form.save()
        # You should perform some redirection here btw.
        return redirect("/success/")
    else:
        print "Errors:", form.errors
        context["form"] = form
else:
    form = ExtraForm(instance=request.user)
    context["form"] = form
return render(request, "updateProfile.html", context)

After update:

You are passing the wrong user to form. request.user is User type whereas you try updating RegisteredUser. You should update the line:

form = ExtraForm(request.POST, instance=request.user)

to

form = ExtraForm(request.POST, instance=RegisteredUser.objects.get(user=request.user))

Same applies to else part too:

form = ExtraForm(instance=RegisteredUser.objects.get(user=request.user))