-->

如何设置在使用通用视图视图模型的一个领域?(How to set a field of the mo

2019-08-03 10:25发布

我有一个模型,其中有一个作者ForeignKey ,因为这样的:

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

我想author在创建约会时,当前登录的用户字段来自动设置。 换句话说,笔者领域不应该出现在我的窗体类:

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

有两个问题:

  1. 如何访问的形式,一般CreateView的,并设置author
  2. 如何判断的形式来保存排除现场与用户输入的读取值一起?

Answer 1:

下面略显简单。 需要注意的是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


Answer 2:

我修改我的通用视图子这样:

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线,合并过载和碱成一个函数(我不是主叫superpost )。

我认为这是解决很常见问题的好办法,并再次我没有写我自己的自定义视图。



文章来源: How to set a field of the model in view using generic views?