【问题标题】:Django: inline formset example from documentationDjango:文档中的内联表单集示例
【发布时间】:2012-08-15 20:14:22
【问题描述】:

我得到了一个提示,可以尝试使用内联表单集来解决问题。 只是在沙盒项目中试验它。我正在尝试复制与 Django 文档中完全相同的example,但它失败了。 :(

型号:

TITLE_CHOICES = (
    ('MR', 'Mr.'),
    ('MRS', 'Mrs.'),
    ('MS', 'Ms.'),
) 

class Author(models.Model):
    name = models.CharField(max_length=100)
    title = models.CharField(max_length=3, choices=TITLE_CHOICES)
    birth_date = models.DateField(blank=True, null=True)

    def __unicode__(self):
        return self.name

class Book(models.Model):
    name = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)**

查看:

def manage_books(request, author_id):
    author = Author.objects.get(pk=author_id)
    BookInlineFormSet = inlineformset_factory(Author, Book)
    if request.method == "POST":
        formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
        if formset.is_valid():
            formset.save()
            # Do something. Should generally end with a redirect. For example:
            return HttpResponseRedirect(author.get_absolute_url())
    else:
        formset = BookInlineFormSet(instance=author)
    return render_to_response("manage_books.html", {        "formset": formset,    })

在管理屏幕中,我成功创建了Author1Author2

Book1Book1b 分配给 Author1
Book2 分配给 Author2

当我尝试它时,我得到一个<class 'Sandbox_App.models.Book'> has no ForeignKey to <class 'Sandbox_App.models.Author'>

追溯:

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/test/1

Django Version: 1.4.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',a
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'Sandbox_App',
 'django.contrib.admin')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/houman/projects/Sandbox/Sandbox_App/views.py" in manage_books
  58.     BookInlineFormSet = inlineformset_factory(Author, Book)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in inlineformset_factory
  817.     fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in _get_foreign_key
  800.             raise Exception("%s has no ForeignKey to %s" % (model, parent_model))

Exception Type: Exception at /test/1
Exception Value: <class 'Sandbox_App.models.Book'> has no ForeignKey to <class 'Sandbox_App.models.Author'>

为什么这不起作用?

非常感谢

【问题讨论】:

标签: django inline-formset


【解决方案1】:

与错误消息所述一样,Book 应该有一个外键给 Author。您正在使用 ManyToManyRelation。

authors = models.ManyToManyField(Author)

我在 shell 中测试了文档中的示例,它可以正常工作。

也看这里:Django inlineformset_factory and ManyToMany fields

【讨论】:

  • 谢谢Jingo,我现在明白了,这是如何工作的。有趣的是,您和我正在为我们的表单集寻找类似的解决方案。所以这个内联表单集毕竟不能成为答案......
猜你喜欢
  • 2019-05-15
  • 1970-01-01
  • 2011-11-30
  • 1970-01-01
  • 2011-07-11
  • 1970-01-01
  • 2016-03-15
  • 2012-06-27
  • 1970-01-01
相关资源
最近更新 更多