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')
我的功能如下所示,用于显示和更新表单。
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() 由于在那里放置打印而被调用,并且它显示在开发服务器中。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
安迪·休谟对你的问题的评论是正确的。
您有一个基于 UserPrivacy 模型的 ModelForm,但您正在向它传递一个 User 实例。
你想做的是这样的:
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: