django - 将值从表单保存到数据库
我正在创建一个自定义个人资料页面,我需要用户能够保存或更新他的个人资料。由于某种原因,当我点击更新配置文件按钮时,出现以下错误:
用户匹配查询不存在。
下面是我的表单、模型和视图文件的代码:
forms.py
class ProfileForm(forms.Form):
profile_name = forms.CharField( max_length=50)
models.py
class UserProfile(models.Model):
user = models.ForeignKey(User)
profile_name = models.CharField(blank=True, max_length=50)
def __unicode__(self):
return u'%s %s' % (self.user, self.profile_name)
views.py
def edit_profile(request):
if 'edit_button' in request.POST:
form = ProfileForm(request.POST)
f_user = User.objects.get(username=request.user.id)
f_profile_name = form.cleaned_data['profile_name']
p = UserProfile(user=f_user, profile_name=f_profile_name)
p.save()
else:
form = ProfileForm()
return render_to_response('userprofile_template.html', locals(), context_instance=RequestContext(request))
知道我做错了什么吗?谢谢你!
I'm creating a custom profile page and I need the user to be able to save or update his profile. For some reason I'm getting the following error when I hit the update profile button:
User matching query does not exist.
Below is the code I have for the forms, models and views files:
forms.py
class ProfileForm(forms.Form):
profile_name = forms.CharField( max_length=50)
models.py
class UserProfile(models.Model):
user = models.ForeignKey(User)
profile_name = models.CharField(blank=True, max_length=50)
def __unicode__(self):
return u'%s %s' % (self.user, self.profile_name)
views.py
def edit_profile(request):
if 'edit_button' in request.POST:
form = ProfileForm(request.POST)
f_user = User.objects.get(username=request.user.id)
f_profile_name = form.cleaned_data['profile_name']
p = UserProfile(user=f_user, profile_name=f_profile_name)
p.save()
else:
form = ProfileForm()
return render_to_response('userprofile_template.html', locals(), context_instance=RequestContext(request))
Any idea what am I not doing right? Thank You!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
用户名大概是
request.user.username
或者只是用户
User.objects.get(id=request.user.id)
实际上我的咖啡屁股在说什么?您的用户对象就在那里!
request.user
:)Username is presumabely
request.user.username
Or, just user
User.objects.get(id=request.user.id)
Actually what is my caffienated ass saying? You have your user object right there!
request.user
: )