Ahmed Wagdi
Ahmed Wagdi

Reputation: 4401

How to control initial value and label of django forms BooleanField

I have a form as (BooleanField) in Django forms, and I need to set it is the initial value (True or false) dynamically, also want to add a label to it. here is my code:

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())

And here is how it looks like, No label nor Initial value for boolean field:

enter image description here

Note: The screenshot are taking from a view where it supposed to have the init value is TRUE

Upvotes: 0

Views: 661

Answers (1)

Chris
Chris

Reputation: 2212

Your form works ok. The problem is in your view

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

This is the GET part of your view, but you are sending POST data to the form. Change the line to

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

Then it should render ok.

Upvotes: 1

Related Questions