Django 在表单中自动设置外键(使用基于类的视图) [英] Django automatically set foreign key in form (with class based views)

查看:25
本文介绍了Django 在表单中自动设置外键(使用基于类的视图)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用一个表单从一个人的页面生成一个新对象(比如一本书),这样新书就会通过外键自动与那个人关联,但是我在正确关联这个人时遇到了麻烦并与表格一起保存.对于我的模型,我有:

I want to use a form to generate a new object (say a Book) from a Person's page such that the new Book is automatically associated with that Person via a foreign key, but I am running into trouble getting the Person correctly associated and saved with the form. For my models, I have:

class Person(models.Model):
    p_id = models.PositiveIntegerField(primary_key=True, unique=True)

class Book(models.Model):
    person = models.ForeignKey(Person)
    title = models.CharField(max_length=100)

然后我有一个自定义表单来创建一本书:

I then have a custom form to create a Book:

class AddBookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ('title', 'person',)
        widgets = {
            'person': forms.HiddenInput,
        }

以及创建 Book 的视图(也给出了 Person 的 pk (p_id)):

And a view to create the Book (which is also given the pk (p_id) of the Person):

class AddBook(CreateView):
    model = Book

我尝试了各种方法来让它发挥作用:

I have tried various things to get this to work:

  • 使用 get_initial 预先填充 Person 字段,但由于某种原因,由于输入设置为隐藏(令人沮丧),这会消失.
  • 修改视图中的 form_valid 方法,但这只发生在表单已经验证之后,所以我需要在此之前添加 Person.
  • 修改表单类中的 clean_person 方法,但只有在表单通过 clean 方法验证后才会发生.
  • Pre-populating the Person field with get_initial, but this disappears for some reason with the input is set to hidden (frustratingly).
  • modifying the form_valid method in the view, but this only occurs after the form has already been validated, so I need to add Person before that.
  • modifying the clean_person method in the form class, but that only occurs after the form has been validated by the clean method.

目前,我正在尝试覆盖 clean 方法.但是,在表单已经发送进行清理之后,我此时不知道如何获取 Person.在视图中,我可以使用 Patient.objects.get(p_id=self.kwargs.get('pk')) 访问它.

Currently, I am trying to override the clean method. However, I don't know how to get the Person at this point, after the form has already been sent for cleaning. In the view, I could access it with Patient.objects.get(p_id=self.kwargs.get('pk')).

有什么方法可以在我的视图中将数据添加到表单中(作为基于类的视图),它不会被删除有什么方法可以访问人或p_id外键此时在clean方法中添加数据?

Is there some way I can add the data to the form in my view (as a class-based view) that it won't get stripped away OR is there some way I can access the Person or p_id foreign key at this point to add the data in the clean method?

推荐答案

你的方法是错误的:这个人不是用户输入的,所以这些信息不应该存在于表单中.您可以按如下方式覆盖 form_valid 方法:

You're going at it the wrong way: the person is not user input, so this information should not reside in the form. You can override the form_valid method as follows:

class AddBook(CreateView):
    model = Book

    def form_valid(self, form):
        form.instance.person_id = self.kwargs.get('pk')
        return super(AddBook, self).form_valid(form)

这将在表单使用的实例上设置 person_id 属性以保存数据,然后调用 super 方法保存该实例并返回重定向.

This will set the person_id attribute on the instance used by the form to save the data, and then call the super method to save that instance and return a redirect.

这篇关于Django 在表单中自动设置外键(使用基于类的视图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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