프로그래밍

django chap2-9 여러가지 필드

freenomad 2022. 1. 9. 16:16
반응형

 

Form의 여러 가지 필드

CharField, EmailField, IntegerField, FloatField, URLField

require 필수항목 설정. require=true면 필수항목으로 설정
min_length, max_length 최소글자수, 최대글자수 설정

 

DateField, TimeField, DateTimeField

시간, 날짜를 일정한 형식으로 입력하지 않으면 안 된다.

날짜 형식 - 2001-01-01, 01/01/2001, 01/01/01

시간 형식 - 12:34, 12:34:56

 

체크박스

BooleanField로 사용 가능

hello/forms.py 수정

class HelloForm(forms.Form):
    check = forms.BooleanField(label='check', required=False)

 

index.html 수정

<body class="container">
    <h1 class="display-4 text-primary">{{title}}</h1>
    <p class="h5 mt-4">{{result|safe}}</p>
    <form action="{% url 'index' %}" method="post">
        {% csrf_token %}
        <table>
        {{ form.as_p }}
        <tr><td></td></tr>
        <input class="btn btn-primary" type="submit" value="click">
    </form>
</body>

hello/views.py 수정

class HelloView(TemplateView):
    
    def __init__(self):
        self.params = {
            'title':'Hello',
            'form':HelloForm(),
            'result':None
        }
        
    def get(self, request):
        return render(request, 'hello/index.html', self.params)

    def post(self, request):
        if ('check' in request.POST):
            self.params['result'] = 'Checked!!'
        else:
            self.params['result'] = 'not checked..'
        self.params['form'] = HelloForm(request.POST)
        return render(request, 'hello/index.html', self.params)

 

3택의 NullBooleanField

hello/forms.py 수정

class HelloForm(forms.Form):
    check = forms.NullBooleanField(label='check')

hello/views.py 수정

def post(self, request):
        chk = ''
        if ('check' in request.POST):
            chk = request.POST['check']    
        self.params['result'] = 'you selected: "' + chk + '".'
        self.params['form'] = HelloForm(request.POST)
        return render(request, 'hello/index.html', self.params)

풀다운 메뉴

hello/forms.py 수정

class HelloForm(forms.Form):
    data = [
        ('one', 'item 1'),
        ('two', 'item 2'),
        ('three', 'item 3'),
    ]
    choice = forms.ChoiceField(label='Choice', choices=data)

hello/views.py 수정

class HelloView(TemplateView):
    
    def __init__(self):
        self.params = {
            'title':'Hello',
            'form':HelloForm(),
            'result':None
        }
        
    def get(self, request):
        return render(request, 'hello/index.html', self.params)

    def post(self, request):
        ch = ''
        if ('choice' in request.POST):
            ch = request.POST['choice']    
        self.params['result'] = 'selected: "' + ch + '".'
        self.params['form'] = HelloForm(request.POST)
        return render(request, 'hello/index.html', self.params)

 

라디오 버튼

hello/forms.py 수정

widget을 사용하는 것이 특징

class HelloForm(forms.Form):
    data = [
        ('one', 'item 1'),
        ('two', 'item 2'),
        ('three', 'item 3')
    ]
    choice = forms.ChoiceField(label='radio', choices=data, widget=forms.RadioSelect())

 

 

선택 리스트

hello/forms.py 수정

widget을 사용하는 것이 특징

class HelloForm(forms.Form):
    data = [
        ('one', 'item 1'),
        ('two', 'item 2'),
        ('three', 'item 3'),
        ('four', 'item 4'),
        ('five', 'item 5')
    ]
    choice = forms.ChoiceField(label='radio', choices=data, widget=forms.Select(attrs={'size':5}))

복수 선택의 경우

hello/forms.py 수정

widget을 사용하는 것이 특징

class HelloForm(forms.Form):
    data = [
        ('one', 'item 1'),
        ('two', 'item 2'),
        ('three', 'item 3'),
        ('four', 'item 4'),
        ('five', 'item 5')
    ]
    choice = forms.ChoiceField(label='radio', choices=data, widget=forms.SelectMultiple(attrs={'size':6}))

hello/views.py 수정

class HelloView(TemplateView):
    
    def __init__(self):
        self.params = {
            'title':'Hello',
            'form':HelloForm(),
            'result':None
        }
        
    def get(self, request):
        return render(request, 'hello/index.html', self.params)

    def post(self, request):
        ch = ''
        if ('choice' in request.POST):
            ch = request.POST.getlist('choice')  
        self.params['result'] = 'selected: "' + str(ch) + '".'
        self.params['form'] = HelloForm(request.POST)
        return render(request, 'hello/index.html', self.params)

getlist를 사용하고 있다.

리스트의 값을 사용하고 싶을 땐?

class HelloView(TemplateView):
    
    def __init__(self):
        self.params = {
            'title':'Hello',
            'form':HelloForm(),
            'result':None
        }
        
    def get(self, request):
        return render(request, 'hello/index.html', self.params)

    def post(self, request):
        ch = ''
        if ('choice' in request.POST):
            ch = request.POST.getlist('choice') 
        result = '<ol class="list-group"><b>selected: </b>'
        for item in ch:
            result += '<li class="list-group-item">' + item + '</li>'
        result += '</ol>'  
        self.params['result'] = result
        self.params['form'] = HelloForm(request.POST)
        return render(request, 'hello/index.html', self.params)

위와 같이 태그 부분을 수정해서 사용할 수 있다. for반복문을 사용.

반응형

'프로그래밍' 카테고리의 다른 글

django chap3-2 데이터베이스 관리툴  (0) 2022.01.10
django chap3-1 모델과 데이터베이스  (0) 2022.01.10
django chap2-8 Form클래스  (0) 2022.01.09
django chap2-7 form송신  (0) 2022.01.09
django chap2-6 뷰 템플릿  (0) 2022.01.08