问题是让内联模型根据其他模型预先选择一些领域。
我们举个例子:
class Document(models.Model):
DOC_TYPES = ((DC1, 'Doc type 1'), (DC2, 'Doc type 2'))
doctype = model.CharField(choices=DOC_TYPES, default=DC1)
class OptionCategory(models.Model):
name = model.CharField()
class Option(models.Model):
document = models.ForeignKey(Document)
option_category = models.ForeignKey(OptionCategory)
some_data = models.CharField()
假设该选项是在文档模型admin中内联定义的。
OptionCategory
是必要的 - 这些可能会由管理员添加 - 我希望有一个文档的创建表单,内联表单中有很多选项模型,因为有选项类别。这可以使用Option
模型管理员中的附加功能轻松实现。问题是:
Document.doctype
中添加类似的doctype字段后基于OptionCategory
) - 最好使用ajax?答案 0 :(得分:4)
models.py
class DocType(models.Model):
name = models.CharField(max_length=255)
def __unicode__(self):
return self.name
class Document(models.Model):
doc_type = models.ForeignKey(DocType)
some_data = models.CharField(max_length=255)
def __unicode__(self):
return self.some_data
class OptionType(models.Model):
name = models.CharField(max_length=255)
doc_type = models.ForeignKey(DocType)
def __unicode__(self):
return self.name
class Option(models.Model):
document = models.ForeignKey(Document)
option_type = models.ForeignKey(OptionType)
some_data = models.CharField(max_length=255)
def __unicode__(self):
return self.some_data
admin.py
class InlineOption(admin.TabularInline):
model = Option
extra = 3
initial = [
{'some_data': 'init_val1', 'option_type': 1},
{'some_data': 'init_val2'},
]
create_from_default = True
def get_formset(self, request, obj=None, **kwargs):
initial = self.initial[:]
class _Form(forms.ModelForm):
form_initial = initial
def __init__(self, *args, **kwargs):
if len(self.form_initial) and not 'instance' in kwargs:
kwargs['initial'] = self.form_initial.pop(0)
return super(_Form, self).__init__(*args, **kwargs)
if self.create_from_default:
if request.method == 'GET':
self.form = _Form
else:
self.form = forms.ModelForm
else:
self.form = _Form
return super(InlineOption, self).get_formset(request, obj, **kwargs)
class AdminDocument(admin.ModelAdmin):
inlines = [InlineOption]