我有一个模型,它有一个作者ForeignKey
,比如:
class Appointment(models.Model):
# ...
author = models.ForeignKey(User)
我希望在为当前登录的用户创建约会时自动设置 author
字段。换句话说,作者字段不应该出现在我的 Form 类中:
class AppointmentCreateForm(ModelForm):
class Meta:
model = Appointment
exclude = ('author')
有两个问题:
- 如何在通用 CreateView 中访问表单并设置
作者
? - 如何告诉表单将排除的字段与从用户输入中读取的值一起保存?
最佳答案
以下内容似乎稍微简单一些。注意 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
关于django - 如何使用通用 View 在 View 中设置模型的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13659508/