Djangoの管理:動的に追加インラインフォームに値を挿入する方法
質問
のは、私はこのモデルを持っているとしましょう。
class Foo(models.Model):
bar = models.ForeignKey(Bar)
currency = models.ForeignKey(Currency) # currency is just an example
is_active = models.BooleanField()
今fooはバーのインラインであると仮定します。そして、私はいつも各通貨の価値を示すためにしたいですか?私は置き換えることができれば、これらの通貨はちょうど隠しフィールドとテキストとして名を返すウィジェットにドロップダウンメニュー。 ですから、例えば、追加ページで、代わりにインラインではこれを示したのます:
- currency drop down menu is_active checkbox
- currency drop down menu is_active checkbox
- currency drop down menu is_active checkbox
それはこのことを示しています:
- currency name 1 is_active checkbox
- currency name 2 is_active checkbox
- currency name 3 is_active checkbox
- currency name 4 is_active checkbox
- currency name 5 is_active checkbox
どのようなことを達成するために正しいアプローチでしょうか?私はいくつかのフォームクラスのメソッドをオーバーライドしなければならないと仮定します。おかげます。
解決 3
私はJavaScriptを使用して、それを解決しました。 表形式または積み重ねられたテンプレートの上部に以下を挿入します。これは、名前の列が名命名されていると仮定します。
{% with inline_admin_formset.opts as i %}
{% if i.pre_filled %}
<script language="JavaScript" type="text/javascript">
jQuery(function($) {
var pre_values = [
{% for name in i.pre_filled %}
{% if forloop.last %}
[{{ name.id }}, "{{ name.name }}"]
{% else %}
[{{ name.id }}, "{{ name.name }}"],
{% endif %}
{% endfor %}
];
$.each( pre_values,
function( i, value ){
$('div.inline-group div.tabular').each(function() {
$("#id_{{ i.verbose_name|lower|cut:" " }}_set-" + i + "-{{ i.pre_field }}").after(value[1]);
$("#id_{{ i.verbose_name|lower|cut:" " }}_set-" + i + "-{{ i.pre_field }}").val(value[0]).hide();
$("#lookup_id_{{ i.verbose_name|lower|cut:" " }}_set-" + i + "-{{ i.pre_field }}").hide();
$("strong").hide();
});
}
);
});
</script>
{% endif %}
{% endwith %}
そして、これはあなたのinline.pyに行きます:
class MyCustomInline(admin.TabularInline):
pre_filled = []
pre_field = ''
def get_fieldsets(self, request, obj=None):
if not obj and self.pre_filled and self.pre_field:
count = self.pre_filled.count()
self.extra = count
self.max_num = count
if self.raw_id_fields:
self.raw_id_fields.append(self.pre_field)
else:
self.raw_id_fields = [self.pre_field]
return super(MyCustomInline, self).get_fieldsets(request, obj)
class FooInline(MyCustomInline):
model = Foo
pre_filled = Currency.objects.all()
pre_field = 'currency'
他のヒント
あなたが常に同じ通貨を使用する場合:
currency = models.ForeignKey(Currency, default = lambda: Currency.objects.get(...)
あなたはハエのサブクラスでフォームを通貨を変更して上書きする場合ののinit のあなたはself.fields['currency']
にあなたの魔法を行うことができる場所。
あなたはフォームクラスでそのフィールドにwidget = forms.HiddenInput()
を使用し、フィールドを非表示にしたい場合。
私はあなたの本当の問題は、それがあなたの質問に答えると思いますが、ありません。通貨の柔軟な取り扱いのための[1]〜[ジャンゴ-通貨]を使用します。
[1]: http://code.google.com/p/django-通貨/ のジャンゴ - 通貨
ここで解決する最初の問題は、各バーのためにFOOSリンク適切なの事前生成があります。あなたはバーの上にsave()メソッドをカスタムでそれを行う、または信号を使用して、または可能性がありBarManager上のバーのファクトリメソッドで...
それを行うのならば、私はあなたの管理者の問題は次のように解決することができると思います:
class FooInline(admin.TabularInline):
formfield_overrides = {models.ModelChoiceField: {'widget': ReadOnlyWidget}}
model = Foo
extra = 0
あなたはどこにここの 1のようなカスタムReadOnlyWidgetを使用すると思います。