Django:如何在通用的创建视图上设置一个隐藏的字段? [英] Django: How to set a hidden field on a generic create view?
问题描述
我正在运行Django 1.6.x
I'm running Django 1.6.x
为了扩展我的用户,我添加了另一个存储数据的模型:
To extend my user I've added another model storing the data:
class UserProfile (models.Model):
user = models.ForeignKey(User)`
height = models.IntegerField(blank=True, null=True)`
现在我想添加一个视图,这是允许用户添加自己的信息在那里开始使用 django.views.generic.edit.CreateView ,但也希望至少提供一个编辑/更新。
Now I wand to add a view, which is allowing the user to add its own infos there. Started with django.views.generic.edit.CreateView, but want also to provide at least the edit/update one to.
所以我添加了导入并创建了一个视图:
So I've added the import and created a view:
from django.views.generic.edit import CreateView, UpdateView
# ....
class UserProfileCreateView(CreateView):
model = UserProfile
fields = ['height']
此外,我还在urls.py中添加了条目:
Also I've added the entry inside urls.py:
url(r'^userprofile/new/$', login_required(UserProfileCreateView.as_view()), name="add_userprofile")
但是现在我坚持如何以正确的方式分配用户ID。我想让这个字段设置在后台。任何提示?
But now I'm stuck on the point how to assign the user ID in the correct way. I want to have this field set in background. Any hints?
推荐答案
你可以这样做:
- 从请求对象获取用户。
- 覆盖UserProfileCreateView类上的form_valid方法,
- 将用户添加到表单并保存。
class UserProfileCreateView(CreateView):
model = UserProfile
fields = ['height']
def form_valid(self, form):
user = self.request.user
form.instance.user = user
return super(UserProfileCreateView, self).form_valid(form)
此代码适用于Python 2.7.x
This code is for Python 2.7.x
这篇关于Django:如何在通用的创建视图上设置一个隐藏的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!