我有一个Django应用程序,我希望能够在多个实例中使用。一个模型(列表)可以有可变数量的字段(对于不同的实例),但是对于实例来说,总是有这些额外的字段。我希望通过管理添加这些额外的字段,因此我创建了如下模型:
class BespokeField (models.Model):
name = models.CharField(
max_length = 20,
verbose_name = "Field Title"
)
def __unicode__(self):
return self.name
class Listing (models.Model):
name = models.CharField (
verbose_name = 'Listing',
max_length = 30
)
slug = models.SlugField (
verbose_name = "Slug",
allow_unicode = True,
unique=True,
blank=True,
null=True
)
class ListingBespokeField (models.Model):
bespoke_field = models.ForeignKey(BespokeField)
listing = models.ForeignKey(Listing)
value = models.CharField (
max_length = 60
)
def __unicode__(self):
return u'%s | %s' % (self.listing.name, self.bespoke_field.name)
理论是管理员指定定制字段,然后以表单形式显示给用户。在管理这是相对简单的,因为我可以假设从用户的情报,所以我的管理员py看起来像:
^{pr2}$这意味着管理员用户必须从下拉列表中选择每个BespokeField中的一个,但我对此并不感到不舒服,因为通过一起使用unique_,可以确保每个BespokeField只有一个。在
我不知道如何做的是把这个以友好的方式呈现给非管理员用户。我想要的是BespokeField.name
在表单上显示为ListingBespokeField.value
的标签。在
这是我在forms.py
(用于列出bespokefield)中的内容。在
class ListingBespokeFieldInline(forms.ModelForm):
class Meta:
model = ListingBespokeField
exclude =['id']
widgets = {
'bespoke_field' : forms.HiddenInput(),
'value' : forms.TextInput(attrs={'class' : 'form-control'})
}
class ListingBespokeFieldForm(forms.ModelForm):
class Meta:
model = ListingBespokeField
exclude = ()
BESPOKE_FIELD_COUNT = len(BespokeField.objects.all())
ListingBespokeFieldInlineFormSet = forms.inlineformset_factory (
Listing,
ListingBespokeField,
form=ListingBespokeFieldInline,
extra = BESPOKE_FIELD_COUNT,
max_num = BESPOKE_FIELD_COUNT,
exclude = ['id'],
can_delete=False,
can_order=False
)
然后,我尝试通过以下模板来呈现:
<table class="table">
{{ bespokefields.management_form }}
{% for form in bespokefields.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tr class="formset_row bespokefield">
<td>
{{ form.listing }}{{ form.id }}{{ form.bespoke_field }}
{{ form.bespoke_field.label }}
</td>
<td>{{ form.value }}</td>
</tr>
{% endfor %}
</table>
这不管用。我需要一些洞察力。在
这是我的解决方案:
相关问题 更多 >
编程相关推荐