【问题标题】:How to control initial value and label of django forms BooleanField如何控制 django 表单 BooleanField 的初始值和标签
【发布时间】: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 的视图

【问题讨论】:

    标签: python django


    【解决方案1】:

    您的表单工作正常。问题在你看来

    else:
        edit_category_form = EditCategoryForm(request.POST, request.FILES, name=current_category.name, is_pos=current_category.is_pos)
        ...
    

    这是您视图的GET 部分,但您正在向表单发送POST 数据。将行改为

    edit_category_form = EditCategoryForm(name=current_category.name, is_pos=current_category.is_pos)
    

    然后它应该可以渲染。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-06
      • 2013-02-22
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      相关资源
      最近更新 更多