Django update model form

I have a model as follows

class UserPrivacy(models.Model):
    user = models.ForeignKey(User)
    profile = models.SmallIntegerField(default=1, choices=PRIVACY_TYPE)
    contact = models.SmallIntegerField(default=1, choices=PRIVACY_TYPE)
    friends = models.SmallIntegerField(default=1, choices=PRIVACY_TYPE)
    location = models.SmallIntegerField(default=1, choices=PRIVACY_TYPE)

My model model is as follows

class PrivacyForm(ModelForm):
    class Meta:
        model = UserPrivacy
        exclude = ('user','location')

My function looks like to display and update the form.

def show_privacy(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/')

    if request.method == 'POST':
        form = PrivacyForm(request.POST, instance=User.objects.get(pk=request.session['id']))
        if form.is_valid():
            form.save()

    else:
        form = PrivacyForm()

    return render_to_response('settings_privacy.html', {'form': form}, context_instance=RequestContext(request))

My user_id in db is 1 .. but when I submit the form, it never updates. I know that form.save () is called because the print is there, and it is displayed on the dev server.

+1
source share
1 answer

Andy Hume was right in the comments on your question.

You have a ModelForm based on the UserPrivacy model, but you pass the user instance to it.

What do you want to do:

form = PrivacyForm(request.POST, instance=UserPrivacy.objects.get(user=request.user)
+8
source

All Articles