Django 用户设置的问题

2014-08-08 14:12:43 +08:00
 ChiangDi
是这样的,我按照[官方的的指南] https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#extending-the-existing-user-model
想建一个用户个人信息设置页面,用户可以设置自己的网站名称,


首先我在 models.py 里面用 OneToOneField 拓展原来的 User:

class UserProfile(models.Model):
user = models.OneToOneField(User)
website = models.URLField(blank=True)
def __unicode__(self):
return "%s's profile" % self.user



然后呢我用 ModelForm :

class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('website')


然后我在 views.py 里面

def settings(request):
if request.method == 'POST':
form = UserProfileForm(request.POST)
user_profile = form.save()
return HttpResponseRedirect("/")
else:
form = UserProfileForm()
return render(request, "settings.html", {'form': form, })


但是问题是那个 form.save() 时只包含了 website 这一项,并没有把user的其他东西存入
UserProfile 中,
所以用户设置填写好以后提交表单后,会显示 "Column 'user_id' cannot be null" 因为它并没有继承原来的user的信息。

所以我该如何做好呢?不知道我有没有说清楚,新人求教...
3447 次点击
所在节点    Django
9 条回复
ChiangDi
2014-08-08 14:15:27 +08:00
为什么编辑主题时的那个选择 markdown 语法不起作用...
ChiangDi
2014-08-08 14:18:57 +08:00
我在 sf.gg 上提了这个问题,排版好点 http://segmentfault.com/q/1010000000631018
wangyongbo
2014-08-08 14:44:44 +08:00
看看这个 https://docs.djangoproject.com/en/dev/topics/forms/modelforms/

首先,每个用户应该已经有了一个UserProfile

form = UserProfileForm(request.POST)

改为
form = UserProfileForm(request.POST, instance = request.user.userprofile)
rockyaow
2014-08-08 14:58:15 +08:00
UserProfile 这个model定义的不对,应该继承abstract为True的 AbstractBaseUser类,这样才能继承其他属性。详情看一下django源码里面auth 的 model
rockyaow
2014-08-08 14:59:13 +08:00
sorry,不太对
wenbinwu
2014-08-08 15:28:41 +08:00
Form里只有fields = ('website')
没有user
ChiangDi
2014-08-08 15:38:20 +08:00
@wangyongbo 非常感谢,我觉得你的想法是对的,按照你的改动后,表单提交后,会显示错误 "User has no profile", 因为他本来是没有profile的 ?
ChiangDi
2014-08-08 23:30:24 +08:00
@wangyongbo 非常感谢,已经谷歌搞定,加了一行 User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
就好了,也不知道是啥意思。。
wangyongbo
2014-08-09 12:59:40 +08:00
@ChiangDi 这句话的意思是说,读取User的 profile 时,使用 lambda u: UserProfile.objects.get_or_create(user=u)[0] 这个函数, 而这个函数,会获取用户的UserProfile. 如果不存在就创建一个新的。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/126761

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX