【问题标题】:How to set a field of the model in view using generic views?如何使用通用视图在视图中设置模型的字段?
【发布时间】:2012-11-19 12:24:59
【问题描述】:

我有一个模型,作者为ForeignKey,例如:

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

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

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

有两个问题:

  1. 如何在通用 CreateView 中访问表单并设置author
  2. 如何告诉表单保存排除的字段以及从用户输入中读取的值?

【问题讨论】:

    标签: django django-generic-views


    【解决方案1】:

    我已经修改了我的通用视图子类:

    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
    • 我需要修改的 post 方法是层次结构中的两个类,因此我需要合并基本代码 self.object = None 行,将重载和基合并为一个函数(我不会在post 中打电话给super)。

    我认为这是解决相当普遍的问题的好方法,而且我再次不必编写自己的自定义视图。

    【讨论】:

      【解决方案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
      

      【讨论】:

      • 正确的签名不会是def get_form(self, form_class**=None**): ?
      • 你是绝对正确的@AllanVital,就像你从 Django 1.8 开始写的一样(我在 1.7 出来时就停止使用 Django)
      猜你喜欢
      • 1970-01-01
      • 2016-07-18
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      相关资源
      最近更新 更多