erp 도전

forms.py , 체크박스 가로 정렬.. attr, choicefield, multiplechoicefield.

나도초딩 2023. 5. 4.

이거 하나 하고 싶은데.... 이게 그렇게 어렵냐..

  • forms.ChoiceField() 하면, <select><option ---------->
  • forms.MultipleChoiceField()

1. 초이스 필드

forms.MultipleChoiceField(widget=forms. 종류)

forms.py

  • attrs={class: "form-check check-inline"} attr로는 감싸는 태그까지는 컨트롤 as_p, as_ul, as_table
  • checkbox 의 경우, <li><label><input></label>이 생성됨. 안에 있는 아이템의 클래스. 즉, <li class="____"><label><input>  를 줄 수가 없어서, 정렬 불가. --> 
yoil_form{
	'다른인풋':{
    		"ㅇㅇ":"aa",
    		},
	'yoil':{
    		"0":"월",
            "1":"화",
            ,,,,,,,,,,
            }
    }
<div>
    {% for checkbox in yoil_form.yoil %}
        {{checkbox}}
    {% endfor %}
</div>
<!-- <div class="btn-group" data-toggle="buttons">  -->
<div>
    {% for checkbox in yoil_form.yoil %}
        <!-- <label class="btn btn-warning"> -->
        {{ checkbox.tag }} {{ checkbox.choice_label }}
        <!-- </label> -->
    {% endfor %}
</div>

{% for checkbox in yoil_form.yoil %}
{ checkbox.tag }} {{ checkbox.choice_label }}

결과값은 동일

{% for checkbox in yoil_form.yoil %}
{{checkbox}}
{% endfor %}
class YoilForm(forms.Form):
    # ids = forms.MultipleChoiceField(widget=forms.MultipleHiddenInput())
    yoil = forms.MultipleChoiceField(
        # widget=forms.CheckboxSelectMultiple(attrs={'inline': True,}),
        widget=forms.CheckboxSelectMultiple(attrs={"class":"list-inline"}),
        choices=((0, "월"),(1, "화"), (2, "수"), (3, "목"), (4, "금"), (5, "토"), (6, "일"),),
    )

views.py

    def get_context_data(self, **kwargs):
        context = super().get_context_data() 
        context['yoil_form'] = YoilForm(initial={'yoil': [0,1,2,3,4,5,6],})

템플릿 :  

<div>{{yoil_form.as_p}}</div>

.as_p

.as_ul

form.as_table :: <tr>

html 결과

<div>
    <p><label>Yoil:</label> </p>
    <ul id="id_yoil" class="list-inline">
        <li>
            <label for="id_yoil_0">
            <input type="checkbox" name="yoil" value="0" class="list-inline" id="id_yoil_0">
                월
            </label>

        </li>
        <li><label>인풋</label></li>
    </ul>
    <p></p>
</div>

 

가로로 배치하는 거 몰라. ㅠㅠ 

widget 이랑 attrs ...아호 어려버. 어려버.... 이건 진짜 뭐냐.. 최악임.

form 에서 초이스필드 사용하기.

(모델폼 사용하면, 초이스필드가 없기 때문에, charfield로 만든다)

 

 

 

[Django] ChoiceField 사용하기

사용자한테 값을 입력 받을 때, checkbox 나 radio 등을 이용해서 값을 받는 경우도 자주 볼 수 있습니다. django 기본 db인 sqlite3 의 경우에는 이 값을 model 에서는 어떤 필드로 받아주는게 좋을까요? 이

ssungkang.tistory.com

참고링크

https://stackoverflow.com/questions/35037454/how-to-manage-post-method-request-in-django

 

How to manage post method request in Django

I cannot get the right data from the following POST form: view.py queryset=ExampleT.objects.filter(id=var_id).order_by('value1') form = HiddenForm(initial={'ids': [o.id for o in queryset]}) return

stackoverflow.com

https://stackoverflow.com/questions/15914488/set-initial-value-of-checkbox-dynamically

 

Set initial value of checkbox dynamically

I have a MultipleChoiceField with a CheckboxSelectMutliple widget: weight_training_days = forms.MultipleChoiceField( help_text=u'(Required) 3 days must be selected', widget=forms.

stackoverflow.com

forms.MultipleChoiceField(
    widget=forms.CheckboxSelectMultiple(attrs={'inline': True,}),
    choices=(
        (0, "

 

class HiddenForm(forms.Form):
ids = forms.MultipleChoiceField(widget=forms.MultipleHiddenInput())

# views.py
queryset=ExampleT.objects.filter(id=var_id).order_by('value1')

form = HiddenForm(initial={'ids': [o.id for o in queryset]})

return render(request, 'test.html', {'form': form})

# forms.py

class HiddenForm(forms.Form):
	ids = forms.MultipleChoiceField(widget=forms.MultipleHiddenInput())

 

# forms.py

class YoilForm(forms.Form):
    # ids = forms.MultipleChoiceField(widget=forms.MultipleHiddenInput())
    요일 = forms.MultipleChoiceField(
        widget=forms.CheckboxSelectMultiple(attrs={
            'inline': True,
        }),
        choices=(
            (0, "월"),
            (1, "화"),
            (2, "수"),
            (3, "목"),
            (4, "금"),
            (5, "토"),
            (6, "일"),
        ),
    )
# views.py
# get_context_data 오버라이딩으로.... 초기값 심어서 폼 보여주기

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['form'] = SearchForm
        context['basiccode'] = self.basiccode
        context['list_form'] = ListForm
        context['yoil_form'] = YoilForm(initial={'요일': [0,1,2,3,4,5,6],})
        
        return context

# queryset 을 choices(체크박스 리스트)로 사용하기

choices=((0, "월"),(1, "화"), (2, "수"), (3, "목"), (4, "금"), (5, "토"), (6, "일"),),

choice = [item.id for item in queryset] : item.id 즉, pk로 리스트를 만든다.

choice = tuple(choice)  : ( 131, 132, 133 ...................141 )

choice = enumerate(choice) : ((0, 131), (1, 132), (2, 133),,,,,,,,,,,,,,,,,,,,,)

class PkForm(forms.Form):
    # ids = forms.MultipleChoiceField(widget=forms.MultipleHiddenInput())
    queryset = TourItem.objects.all()
    choice = [o.id for o in queryset]
    choice = tuple(choice)
    choice = enumerate(choice)
    print(choice)
    요일 = forms.MultipleChoiceField(
        widget=forms.CheckboxSelectMultiple(attrs={
            'inline': True,
        }),
        choices = choice
    )

 

댓글