django更新模型 [英] django update modelform
本文介绍了django更新模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模型如下
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)
我的模型形式如下
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))
我的数据库中的user_id为1 ..但是当我发布表单时,它永远不会被更新。我知道form.save()被调用,因为在那里打印出来,它显示在dev服务器中。
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.
推荐答案
Andy Hume在您的问题的评论中是正确的。
Andy Hume was correct in the comments to your question.
您有一个基于UserPrivacy模型的ModelForm,但您传递一个User的实例。
You have a ModelForm based on the UserPrivacy model, yet you are passing it an instance of User.
你想做的是这样的:
form = PrivacyForm(request.POST, instance=UserPrivacy.objects.get(user=request.user)
这篇关于django更新模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文