我的参数模型如下:
class Parameter(models.Model):
spot = models.ForeignKey(Spot, related_name = 'spot_parameters', verbose_name = _("Spot"))
parameter = models.ForeignKey(ParameterTemplate, verbose_name = _("Parameter"))
value = models.CharField(max_length = 255, db_index = True, verbose_name = _("Value"))
is_auto_generated = models.BooleanField(default = False, verbose_name = _("Is auto generated"))
和ParameterTemplate模型:
class ParameterTemplate(PositionMixin):
DATA_TYPE_CHOICE = (
('int', "int"),
('decimal', "decimal"),
('text', "text"),
('list', "list"),
('size', "size"),
('boolean', "boolean"),
)
name = models.CharField(max_length = 255, verbose_name = _("Name"))
data_type = models.CharField(
max_length=50,
choices=DATA_TYPE_CHOICE,
db_index=True,
verbose_name=_("Data type")
)
values = models.CharField(max_length = 255, blank = True, null = True, verbose_name = _("Value list"))
glyph_class = models.CharField(max_length = 255, blank = True, null = True, verbose_name = _("Icon"))
创建表单时遇到问题。
例如,如果DATA_TYPE_CHOICE是参数的布尔值,我想在表单复选框中显示,而不是TextInput
@EDIT
参数表单视图
@login_required @secure_required def account_spot_parameters_change(request,spot_id): spot = get_object_or_404(Spot,id = spot_id,user = request.user)
title = _("Spot parameters")
ParameterFormSet = inlineformset_factory(Spot, Parameter, form = ParameterForm, extra = 0)
if request.method == 'POST':
formset = ParameterFormSet(request.POST, instance = spot)
if formset.is_valid():
formset.save()
formset = None
messages.success(request, _("Your changes have been saved."))
else:
messages.error(request, _("Form is not filled correctly. Please check the highlighted fields."))
else:
formset = ParameterFormSet(instance = spot)
extra_context = {
'spot': spot,
'title': title,
'formset': formset,
'mode': 'parameters',
}
return shortcuts.render(request, 'account_spot_change.html', extra_context)
ParameterForm
class ParameterForm(forms.ModelForm):
class Meta:
model = Parameter
fields = ('parameter', 'value')
def __init__(self, *args, **kwargs):
super(ParameterForm, self).__init__(*args, **kwargs)
add_widget_css_class(self, 'form-control')
模板
% for form in formset %}
{% for field in form.hidden_fields %}
{{ field }}
{% endfor %}
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
{{ form.parameter }}
</div>
<div class="col-sm-3">
{{ form.value }}
</div>
<div class="col-sm-1 text-center">
{{ form.DELETE }}
</div>
</div>
{% endfor %}