django - 如何使用通用 View 在 View 中设置模型的字段?

标签 django django-generic-views

我有一个模型,它有一个作者ForeignKey,比如:

class Appointment(models.Model):
    # ...
    author = models.ForeignKey(User)

我希望在为当前登录的用户创建约会时自动设置 author 字段。换句话说,作者字段不应该出现在我的 Form 类中:

class AppointmentCreateForm(ModelForm):
    class Meta:
        model = Appointment
        exclude = ('author')

有两个问题:

  1. 如何在通用 CreateView 中访问表单并设置作者
  2. 如何告诉表单将​​排除的字段与从用户输入中读取的值一起保存?

最佳答案

以下内容似乎稍微简单一些。注意 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/

相关文章:

python 只接受 1 个参数(给定 2 个)

python - 覆盖 django rest 泛型 CreateAPIView 中的创建方法

Django 表单前缀与基于类的通用 View

django - 如何判断我是否正在使用模板中的 django 通用 View (CreateView 与 UpdateView)进行创建或更新?

python - Django查询集在查询中获取空值

Django 的 forms.Form 与 forms.ModelForm

python - 测试 Django View 函数

django - 关于在 Piston 中使用 OAuth 的任何好的教程?

django - 禁用 Django 的 CreateView 中的表单字段

django - 我应该在 Django 中测试我的通用 DetailView