我想要一个使用django形式的预填充单片机。但是不能制作它。我可以像这样传递模型并检查它是真还是假。但是如何使用djangoform呢。
<input type="radio" value="True" name="power_windows"
{% if interiorfeatures.power_windows %}checked="true"{% endif %}>Yes
我的代码示例如下所示
class InteriorfeaturesForm(forms.ModelForm):
class Meta:
model = InteriorFeatures
fields = ['power_steering', 'power_windows']
power_steering =forms.ModelChoiceField(queryset=InteriorFeatures.objects.all(),
widget=forms.RadioSelect())
模型
---
class InteriorFeatures(models.Model):
class Meta:
db_table = 'interior_features'
variant = models.ForeignKey(Variant)
power_steering = models.BooleanField(default=False)
power_windows = models.BooleanField(default=False)
try:
interiorfeatures = InteriorFeatures.objects.get(variant=variant)
except InteriorFeatures.DoesNotExist:
interiorfeatures = None
interiorform = InteriorfeaturesForm(instance=interiorfeatures)
return render(request, 'general/specifications.html',
{'dimensionsform': DimensionForm, 'engineform': EngineForm, 'brakeform': BrakeForm,
'capacityform': CapacityForm, 'mileageform': MileageForm, 'priceform': PriceForm,
'steeringform': SteeringForm, 'interiorform': interiorform, 'interiorfeatures': interiorfeatures,
'variant': variant, 'price': price, 'steering': steering, 'wheel': wheel, 'wheelform': WheelForm,
'dimensions': dimensions, 'engine': engine, 'brake': brake, 'capacity': capacity,
'mileage': mileage})
- {{interiorform.power_steering}}
答案 0 :(得分:0)
您只需将power_windows
添加到表单字段中,如下所示:
class InteriorfeaturesForm(forms.ModelForm):
class Meta:
model = InteriorFeatures
fields = ['power_steering', 'power_windows']
power_steering =forms.ModelChoiceField(queryset=InteriorFeatures.objects.all(),
widget=forms.RadioSelect())
power_windows = forms.BooleanField()
默认情况下它会给你一个复选框,但如果你坚持使用单选按钮,你可以这样做:
power_windows = forms.TypedChoiceField(coerce=lambda x: x == 'True',
choices=((False, 'False'), (True, 'True')),
widget=forms.RadioSelect)