2017-02-15 6 views
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でオブジェクトを取得し、リストに必要な情報を格納し、そこにはテンプレートがありますが、それは私にはかなり恐ろしいようです。

これを行うにはより良い方法がありますか?

+0

私ができるが行われあなたが求めていることを理解していない。何がequals/ifnotequal文のために入れ子になっているのでしょうか?そして、 '__str__'は、モデル多元選択フィールドのデフォルト表現です。これは多対多フィールドがフォーム上で使用するものです。 '{{field}}'だけを試してみましたか? –

+0

カテゴリの{{field}}は私に選択ボックスを与えます。アカウントごとに異なるアカウントをドロップダウンすると、選択したアカウント(ドロップボックスなし)と選択したカテゴリ(選択なし)のみを表示します。私は変更や情報を入力したくないので、トランザクションのすべての属性をテキストとして表示したいだけです。 – Lomtrur

+2

なぜフォームを使用していますか? –

答えて

0

コメントのおかげで、私がやっていたことはかなりばかげて無意味だと分かりました。

これは動作します:

1)すべての取引が

transactions = Transaction.objects.for_account(account_id) 

2)

context = {"transactions":transactions,} 
    return render(request, "transactions/transactions_for_account.html", context) 

3)アクセス属性をテンプレートに渡すオブジェクトを取得し、

{% for transaction in transactions %} 
    <tr> 
    <td class="tg-6k2t">{{ transaction.account }}</td> 
    <td class="tg-6k2t">{{ transaction.categories }}</td> 
    <td class="tg-6k2t">{{ transaction.date }}</td> 
    <td class="tg-6k2t">{{ transaction.payee }}</td> 
    <td class="tg-6k2t">{{ transaction.comment }}</td> 
    <td class="tg-6k2t">{{ transaction.outflow }}</td> 
    <td class="tg-6k2t">{{ transaction.inflow }}</td> 
    <td class="tg-6k2t">{{ transaction.cleared }}</td> 
    </tr> 
    {% endfor %} 
関連する問題