django update modelform

青春壹個敷衍的年華 提交于 2019-11-30 21:12:17

问题


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 modelform is as follows

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

My function looks like this 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 the db is 1.. but when I post a form it never gets updated. I know form.save() gets called due to putting a print there and it gets shown in the dev server.


回答1:


Andy Hume was correct in the comments to your question.

You have a ModelForm based on the UserPrivacy model, yet you are passing it an instance of User.

What you want to do is this:

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


来源:https://stackoverflow.com/questions/631722/django-update-modelform

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!