【发布时间】:2020-04-16 01:29:26
【问题描述】:
我在 Django 表单中有一个表单为 (BooleanField),我需要将其动态设置为初始值(True 或 false),还想为其添加标签。这是我的代码:
views.py
def category_edit(request, pk):
current_category = get_object_or_404(Category, pk=pk)
edit_category_form = EditCategoryForm(request.POST, request.FILES, name=current_category.name,
is_pos=current_category.is_pos)
if request.method == "POST":
if edit_category_form.is_valid():
pass
else:
edit_category_form = EditCategoryForm(request.POST, request.FILES, name=current_category.name,
is_pos=current_category.is_pos)
context = {
'current_category': current_category,
'edit_category_form': edit_category_form,
}
return render(request, 'product/category_edit.html', context)
forms.py
class EditCategoryForm(forms.Form):
def __init__(self, *args, **kwargs):
self.the_name = kwargs.pop('name')
self.is_pos = kwargs.pop('is_pos')
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs = {
'class': 'form-control',
'value': self.the_name
}
self.fields['is_pos'].initial = self.is_pos
self.fields['is_pos'].label = _('View in Point of sale')
name = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
}))
image = forms.ImageField(widget=forms.FileInput(attrs={
'class': 'form-control',
}))
is_pos = forms.BooleanField(widget=forms.CheckboxInput())
这是它的样子,布尔字段没有标签也没有初始值:
注意: 屏幕截图取自它应该具有初始值为 TRUE 的视图
【问题讨论】: