在 Google App Engine 中的 ModelForm 中设置父级

发布于 2024-08-18 09:36:47 字数 94 浏览 3 评论 0原文

我想在通过 ModelForm 创建的实体中创建实体组关系。

如何传递父实例并在 ModelForm 中设置 parent= 属性?

I want to create an Entity Group relationship in an Entity that is being created through a ModelForm.

How do I pass the parent instance and set the parent= attribute in the ModelForm?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

So要识趣 2024-08-25 09:36:47

我很想看看您是否能找到解决这个问题的好方法。我自己的解决方案远非优雅,是这样做的:

book = models.Book(title='Foo')
chapter = models.Chapter(parent=book, title='dummy')
form = forms.ChapterForm(request.POST, request.FILES, instance=chapter)

基本上,我首先创建一个具有正确父关系的虚拟对象(在本例中为chapter),然后将其作为 传递表单构造函数的实例 参数。该表单将使用请求中给出的数据覆盖我用于创建虚拟对象的一次性数据。最后,为了获得真正的子对象,我做了这样的事情:

if form.is_valid():
    chapter = form.save()
    # Now chapter.parent() == book

I'll be interested to see if you get any good solutions to this problem. My own solution, which is far from elegant, is to do this:

book = models.Book(title='Foo')
chapter = models.Chapter(parent=book, title='dummy')
form = forms.ChapterForm(request.POST, request.FILES, instance=chapter)

Basically, I first create a dummy object (chapter in this case) with the correct parent relationship and then pass that as the instance argument to the form's constructor. The form will overwrite the throwaway data I used to create the dummy object with the data given in the request. At the end, to get the real child object, I do something like this:

if form.is_valid():
    chapter = form.save()
    # Now chapter.parent() == book
不知在何时 2024-08-25 09:36:47

我对 djangoforms.ModelForm 进行子类化并添加了一个创建方法*:

class ModelForm(djangoforms.ModelForm):
  """Django ModelForm class which uses our implementation of BoundField.
  """

  def create(self, commit=True, key_name=None, parent=None):
    """Save this form's cleaned data into a new model instance.

    Args:
      commit: optional bool, default True; if true, the model instance
        is also saved to the datastore.
      key_name: the key_name of the new model instance, default None
      parent: the parent of the new model instance, default None

    Returns:
      The model instance created by this call.
    Raises:
      ValueError if the data couldn't be validated.
    """
    if not self.is_bound:
      raise ValueError('Cannot save an unbound form')
    opts = self._meta
    instance = self.instance
    if self.instance:
      raise ValueError('Cannot create a saved form')
    if self.errors:
      raise ValueError("The %s could not be created because the data didn't "
                       'validate.' % opts.model.kind())
    cleaned_data = self._cleaned_data()
    converted_data = {}
    for name, prop in opts.model.properties().iteritems():
      value = cleaned_data.get(name)
      if value is not None:
        converted_data[name] = prop.make_value_from_form(value)
    try:
      instance = opts.model(key_name=key_name, parent=parent, **converted_data)
      self.instance = instance
    except db.BadValueError, err:
      raise ValueError('The %s could not be created (%s)' %
                       (opts.model.kind(), err))
    if commit:
      instance.put()
    return instance

用法很简单:

book = models.Book(title='Foo')
form = forms.ChapterForm(request.POST)
chapter = form.create(parent=book)

请注意,我没有复制/粘贴允许您在 request.POST 中指定 key_name 的代码,而是将其作为参数传递给 create。

* 代码是根据 google.appengine.ext.db.djangoforms 中原始 modelform 的 save 方法修改的。

I subclassed djangoforms.ModelForm and added a create method*:

class ModelForm(djangoforms.ModelForm):
  """Django ModelForm class which uses our implementation of BoundField.
  """

  def create(self, commit=True, key_name=None, parent=None):
    """Save this form's cleaned data into a new model instance.

    Args:
      commit: optional bool, default True; if true, the model instance
        is also saved to the datastore.
      key_name: the key_name of the new model instance, default None
      parent: the parent of the new model instance, default None

    Returns:
      The model instance created by this call.
    Raises:
      ValueError if the data couldn't be validated.
    """
    if not self.is_bound:
      raise ValueError('Cannot save an unbound form')
    opts = self._meta
    instance = self.instance
    if self.instance:
      raise ValueError('Cannot create a saved form')
    if self.errors:
      raise ValueError("The %s could not be created because the data didn't "
                       'validate.' % opts.model.kind())
    cleaned_data = self._cleaned_data()
    converted_data = {}
    for name, prop in opts.model.properties().iteritems():
      value = cleaned_data.get(name)
      if value is not None:
        converted_data[name] = prop.make_value_from_form(value)
    try:
      instance = opts.model(key_name=key_name, parent=parent, **converted_data)
      self.instance = instance
    except db.BadValueError, err:
      raise ValueError('The %s could not be created (%s)' %
                       (opts.model.kind(), err))
    if commit:
      instance.put()
    return instance

Usage is simple:

book = models.Book(title='Foo')
form = forms.ChapterForm(request.POST)
chapter = form.create(parent=book)

Note that I did not copy/paste the code that lets you specify the key_name in request.POST, instead I have it passed as an argument to create.

* Code is modified from the save method of the original modelform in google.appengine.ext.db.djangoforms.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文