3
から属性を取得します。このモデルではジャンゴ - モデルオブジェクトは、私がModelFormSet持っているのModelForm
TransactionFormSet = modelformset_factory(Transaction, exclude=("",))
:
class Transaction(models.Model):
account = models.ForeignKey(Account)
date = models.DateField()
payee = models.CharField(max_length = 100)
categories = models.ManyToManyField(Category)
comment = models.CharField(max_length = 1000)
outflow = models.DecimalField(max_digits=10, decimal_places=3)
inflow = models.DecimalField(max_digits=10, decimal_places=3)
cleared = models.BooleanField()
そして、これはテンプレートです:
{% for transaction in transactions %}
<ul>
{% for field in transaction %}
{% ifnotequal field.label 'Id' %}
{% ifnotequal field.value None %}
{% ifequal field.label 'Categories' %}
// what do i do here?
{% endifequal %}
<li>{{ field.label}}: {{ field.value }}</li>
{% endifnotequal %}
{% endifnotequal %}
{% endfor %}
</ul>
{% endfor %}
ビュー:
def transactions_on_account_view(request, account_id):
if request.method == "GET":
transactions = TransactionFormSet(queryset=Transaction.objects.for_account(account_id))
context = {"transactions":transactions}
return render(request, "transactions/transactions_for_account.html", context)
ページ上のすべての取引情報を表示したいと思います。 「取引」の「勘定」プロパティと「カテゴリ」を一覧表示するにはどうすればよいですか? 現在のところ、テンプレートにはIDのみが表示されていますので、ユーザーの表現が好きです(好ましくはstr()メソッドから)。
私が見ることができる唯一の方法は、FormSetを繰り返し、アカウントとカテゴリオブジェクトのIDを取得し、IDでオブジェクトを取得し、リストに必要な情報を格納し、そこにはテンプレートがありますが、それは私にはかなり恐ろしいようです。
これを行うにはより良い方法がありますか?
私ができるが行われあなたが求めていることを理解していない。何がequals/ifnotequal文のために入れ子になっているのでしょうか?そして、 '__str__'は、モデル多元選択フィールドのデフォルト表現です。これは多対多フィールドがフォーム上で使用するものです。 '{{field}}'だけを試してみましたか? –
カテゴリの{{field}}は私に選択ボックスを与えます。アカウントごとに異なるアカウントをドロップダウンすると、選択したアカウント(ドロップボックスなし)と選択したカテゴリ(選択なし)のみを表示します。私は変更や情報を入力したくないので、トランザクションのすべての属性をテキストとして表示したいだけです。 – Lomtrur
なぜフォームを使用していますか? –