【发布时间】:2012-04-17 13:27:33
【问题描述】:
如何在自动生成的表单中设置字段的初始值,以便在显示表单之前添加 Django 模型实例?我正在使用 Django 1.3.1。
我的模型如下:
class Foo(models.Model):
title = models.CharField(max_length=50)
description = models.TextField()
现在的管理表单真的没什么特别的
class FooAdmin(admin.ModelAdmin):
ordering = ('title',)
当我使用管理页面添加新的 Foo 实例时,我得到了一个不错的表单,其中包含用于标题和描述的空字段。我想要的是描述字段设置有我通过调用函数获得的模板。
我目前最好的尝试是这样的:
def get_default_content():
return 'this is a template for a Foo description'
class FooAdminForm(django.forms.ModelForm):
class Meta:
model = Foo
def __init__(self, *args, **kwargs):
kwargs['initial'].update({'description': get_default_content()})
super(FooAdminForm, self).__init__(self, *args, **kwargs)
class FooAdmin(admin.ModelAdmin):
ordering = ('title',)
form = FooAdminForm
但是如果我尝试这个,我会得到这个 Django 错误:
AttributeError at /admin/bar/foo/add/
'FooForm' object has no attribute 'get'
Request Method: GET
Request URL: http://localhost:8000/admin/bar/foo/add/
Django Version: 1.3.1
Exception Type: AttributeError
Exception Value: 'FooForm' object has no attribute 'get'
Exception Location: /www/django-site/venv/lib/python2.6/site-packages/django/forms/widgets.py in value_from_datadict, line 178
我不知道这里出了什么问题,以及我应该怎么做才能让它工作。我还觉得这个错误很奇怪(除了我完全看到它)是我的代码中根本没有 FooForm?
【问题讨论】: