03_Web

[Django] forms에 체크박스 넣는방법

chuu_travel 2025. 5. 20. 15:39
728x90
Django forms에 체크박스 넣는방법

 

 

# forms.py

 

from django import forms

...

#회원가입폼
class SignupForm(forms.Form):
    username = forms.CharField(min_length=3, label="아이디")
    password1 = forms.CharField(widget=forms.PasswordInput, min_length=4, label="비밀번호")
    password2 = forms.CharField(widget=forms.PasswordInput, min_length=4, label="비밀번호 확인")
   
    genre_choices = [
        ('인문학','인문학'),
        ('에세이','에세이'),
        ('사회과학','사회과학'),
        ('소설/시/희곡','소설/시/희곡'),
        ('만화','만화'),
        ('자기계발','자기계발'),
        ('경제경영','경제경영'),
        ('수험서/자격증','수험서/자격증'),
        ('역사','역사'),
        ('어린이','어린이'),
        ('예술/대중문화','예술/대중문화'),
        ('외국어','외국어'),
        ('과학','과학'),
        ('좋은부모','좋은부모'),
        ('유아','유아'),
        ('고전','고전'),
        ('청소년','청소년'),
        ('건강/취미','건강/취미'),
        ('컴퓨터/모바일','컴퓨터/모바일'),
        ('종교/역학','종교/역학'),
        ('요리/살림','요리/살림'),
        ('여행','여행'),
        ('대학교재/전문서적','대학교재/전문서적'),
    ]

    genre = forms.MultipleChoiceField(
        label="선호하는 장르(중복선택가능)",
        choices=genre_choices,
        widget=forms.CheckboxSelectMultiple,
        required=False,
    )

 

views.py
from django.shortcuts import render, redirect

from users.forms import SignupForm

...


def signup(request):
    form = SignupForm()
    context = {
        "form" : form,
    }

    return render(request, "users/signup.html", context)

 

 

signup.html
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>회원가입</title>
</head>
<body>
    <h1>회원가입</h1>
    <form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">회원가입</button>
        <button type="reset">취소</button>
    </form>
   
</body>
</html>

 

728x90