私は、1つまたは 個の属性で構成されたたくさんのアイテムを含むサンドボックスを持っています。各属性は、特定の属性タイプ(色、形状など)に属します。 AttributeTypesとともにグループ化されたAttributesを使用してフォームをレンダリングする方法が失われています。多くの種類から多くの選択肢をタイプ別にグルーピングする
モデル
class Sandbox(models.Model):
item = models.ForeignKey('Item')
class Item(models.Model):
name = models.CharField()
sandbox = models.ForeignKey(Sandbox)
attributes = models.ManyToManyField('Attribute')
class Attribute(models.Model):
name = models.CharField()
type = models.ForeignKey('AttributeType')
class AttributeType(models.Model):
name = models.CharField()
class ItemAttribute(models.Model):
# intermediary model to hold references
item = models.ForeignKey(Item)
type = models.ForeignKey(AttributeType)
attribute = models.ForeignKey(Attribute)
のModelForm
class Sandbox(ModelForm):
class Meta:
model = Sandbox
のみ属性の型ごとに選択肢が存在する場合があります。たとえば、あるものは1つの色 または1つの形状しか持つことができません。
AttributeType Attribute Users choice
color
red
blue [x]
green
shape
shape
triangular
squared [x]
spherical
これは固まっていました。これらの属性をフォーム内でグループ化するにはどうすればできますか。ラジオボタンを使用してタイプごとに1つの属性のみを選択するにはどうすればよいですか? 単純なモデル表現を使用していた私の元の考えは、おそらくここでは不足していますか? 私はドキュメント、StackOverflow、Googleを試しましたが、運はありません。
ヒントとアイデアを歓迎します。
私のソリューション
私は私のニーズを満たすソリューションを構築。 @bmihelacは、カスタムフォームを作成するためのファクトリメソッドを作成する方法について、この記事の良い方向を指摘しました。私は、このファクトリメソッドを呼び出して、フォームを起動します
def make_sandbox_form(item):
def get_attributes(item):
item_attributes = ItemAttribute.objects.filter(item=item)
# we want the first attribute type
_attr_type = item_attributes[0].attribute.all()[0].attribute_type
choices = [] # holds the final choices
attr_fields = {} # to hold the final list of fields
for item_attrs in item_attributes.all():
attributes = item_attrs.attribute.all().order_by('attribute_type')
for attr in attributes:
print attr.attribute_type, ' - ' , _attr_type
if attr.attribute_type == _attr_type:
choices.append((attr.pk, attr.value))
else:
d = {u'%s' % _attr_type : fields.ChoiceField(choices=choices, widget=RadioSelect)}
attr_fields = dict(attr_fields.items() + d.items())
# set the _attr_type to new type and start over with next attribute type
_attr_type = attr.attribute_type
choices = []
return attr_fields
form_fields = {
'item' : fields.IntegerField(widget=HiddenInput),
}
form_fields = dict(form_fields.items() + get_attributes(item).items())
return type('SandboxForm', (forms.BaseForm,), { 'base_fields' : form_fields})
[下記参照]:= make_sandbox_form フォーム()
http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/
(ウィッシュ私はすべてが、私は欠けているStackOverflowの新人であることをupvoteことができ
あなたは[ 'regroup'](https://docs.djangoproject.com/en/dev/ref/templates/builtins/で見たことがありますか? from = olddocs#regroup)テンプレートタグ(属性でグループ化できるようにする) –
はい、私はフォームを使って実装する方法を見つけることができません。私は考えているのは、この問題は新しいフォームのレンダリング方法を作ることで解決できるということです...質問はどうですか... – droidballoon