swedishfished swedishfished - 2 years ago 81
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():
print ("yes")
print ("newform is ")
form = ExtraForm(instance=request.user)
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?


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,


class RegisterUser(models.Model):

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)],
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 Source

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():
        # You should perform some redirection here btw.
        return redirect("/success/")
        print "Errors:", form.errors
        context["form"] = form
    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)


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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download