我有一个模型,其中有一个作者ForeignKey
,因为这样的:
class Appointment(models.Model):
# ...
author = models.ForeignKey(User)
我想author
在创建约会时,当前登录的用户字段来自动设置。 换句话说,笔者领域不应该出现在我的窗体类:
class AppointmentCreateForm(ModelForm):
class Meta:
model = Appointment
exclude = ('author')
有两个问题:
- 如何访问的形式,一般CreateView的,并设置
author
? - 如何判断的形式来保存排除现场与用户输入的读取值一起?
下面略显简单。 需要注意的是self.request获取在设定View.as_view
class AppointmentCreateView(CreateView):
model=Appointment
form_class = AppointmentCreateForm
def get_form(self, form_class):
form = super(AppointmentCreateView, self).get_form(form_class)
# the actual modification of the form
form.instance.author = self.request.user
return form
我修改我的通用视图子这样:
class AppointmentCreateView(CreateView):
model=Appointment
form_class = AppointmentCreateForm
def post(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
# the actual modification of the form
form.instance.author = request.user
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
这里有几个重要的部分:
- 我修改的形式
instance
字段,它认为将是保存实际的模型。 - 你当然可以摆脱的
form_class
- 我已经需要修改后的方法是两类上述层次结构,所以我需要合并基本代码和
self.object = None
线,合并过载和碱成一个函数(我不是主叫super
在post
)。
我认为这是解决很常见问题的好办法,并再次我没有写我自己的自定义视图。