0

テンプレート内のさまざまなフィールドを区別するために後で使用できるモデル フィールドにいくつかの属性を書き込むことは可能ですか?

model.py

from django.db import models

class Person(models.Model):
    first_name = models.CharField("i am the Label", max_length=30)
    last_name = models.CharField("i am other Label", max_length=30, customattr="Custom")

フォーム.py

class PersonForm(ModelForm):
    class Meta:
        Person

template.html

<form action="" method="post">{% csrf_token %}
     {% for field in form %}
         {% ifequal field.customattr 'Custom' %} # HOW COULD THIS WORK?
            <p>Hello world.</p>
            {{ field }}
         {% else %}
            <p>This is not Custom</p>
            {{ field }}
         {% endifequal %}
     {% endfor %}
 <input type="submit" value="Submit" />
 </form>

ヒントはありますか?

4

2 に答える 2

0

なぜあなたがこれをやりたいのか理解できません。カスタム html を ModelForm フィールドに定義したい場合は、次のようにオーバーライドできます。

class PersonForm(ModelForm):
    class Meta:
        Person
    first_name = forms.CharField(
        required = True,
        widget   = forms.TextInput(attrs={'style':'width:100px;'},
    )

このように、HTML をどのようにレンダリングしたいかを Django に伝えることができます。ドキュメントで詳細を確認できますhttps://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets

于 2013-05-14T10:35:18.547 に答える