如何使用通用视图设置模型的一个字段? [英] How to set a field of the model in view using generic views?

查看:89
本文介绍了如何使用通用视图设置模型的一个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,它有一个作者 ForeignKey ,因此:

I have a model, which has an author ForeignKey, as such:

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

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

I want the author field to be set automatically when creating appointment to currently logged-in user. In other words, the author field should not appear in my Form class:

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

有两个问题:


  1. 如何访问通用CreateView中的表单并设置作者

  2. 如何使用表单保存排除的字段以及从用户输入读取的值?


推荐答案

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

I've modified my generic view subclass as such:

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)

这里有几个重要的部分:

There are few important parts here:


  • 我修改了实例字段,其中包含要保存的实际模型。

  • 你可以摆脱 form_class

  • 我需要修改的post方法是以上级别的类,所以我需要结合基础代码 self.object = None 行,将重载和基数合并成一个函数(我没有在 post 中调用 super

  • I modified form instance field, which holds the actual model that's going to be saved.
  • You can of course get rid of the form_class
  • The post method that I've needed to modify was two classes above in hierarchy, so I needed to incorporate the base code and the self.object = None line, merging the overload and base into one function (I'm not calling super in post).

我认为这是解决常见问题的好方法,而且我再也不必自己编写自己的视图。

I think it's a good way to solve pretty common problem, and once again I don't have to write my own custom view.

这篇关于如何使用通用视图设置模型的一个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆